A small seating chart uses rows and columns.
What You Need to Understand
Nested lists allow a list to contain other lists. A rectangular two-dimensional structure can be indexed as [row][column], but Python does not enforce equal-length rows.
When to Use It
A small seating chart uses rows and columns.
Step-by-Step Python Example
seats = [["A1", "A2"], ["B1", "B2"]]
print(seats[1][0])
seats[0][1] = "Reserved"
for row in seats:
print(row)
How the Example Works
Indexing accesses row B then its first seat, while the assignment changes the second seat of row A.
Example Output
B1
['A1', 'Reserved']
['B1', 'B2']
[[0, 0, 0], [0, 0, 9], [0, 0, 0]]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
grid = [[0 for column in range(3)] for row in range(3)]
grid[1][2] = 9
print(grid)
Important Behavior and Edge Cases
Avoid building a grid with [[0] * columns] * rows when rows will change: it repeats references to the same inner list.
Try It Yourself
Create a 3-by-3 zero matrix with a comprehension and modify one cell.
Common Beginner Mistakes
- Avoid building a grid with
[[0] * columns] * rowswhen rows will change: it repeats references to the same inner list. - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- Nested lists allow a list to contain other lists.
- Indexing accesses row B then its first seat, while the assignment changes the second seat of row A.
- Avoid building a grid with
[[0] * columns] * rowswhen rows will change: it repeats references to the same inner list.