Nested Structures
Provided Files
- NestedData.pdf
- Python Tutor – to visualize the examples below
Model 1: Nested Lists
grid = [
[' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' '],
['Y', ' ', ' ', ' ', 'Y', 'Y', ' '],
['R', ' ', ' ', 'Y', 'R', 'R', ' '],
['R', 'R', 'Y', 'R', 'Y', 'R', ' '],
['R', 'Y', 'R', 'Y', 'Y', 'Y', 'R'],
]
Model 2: Nested Loops
groceries = ["Apples", "Milk", "Flour", "Chips"]
for item in groceries:
print("Don't forget the", item)
count = 0
for row in grid: # outer loop
print("row =", row)
for cell in row: # inner loop
print("cell =", cell)
if cell == ' ':
count += 1
print(count, "spaces remaining")
Question 13