A grid initializes two rows of three empty cells.
What You Need to Understand
Multiplying a list repeats references to its existing elements. For a list containing mutable nested lists, this can create shared rows rather than independent rows.
When to Use It
A grid initializes two rows of three empty cells.
Step-by-Step Python Example
incorrect_grid = [[0] * 3] * 2
incorrect_grid[0][0] = 9
print(incorrect_grid)
correct_grid = [[0] * 3 for row in range(2)]
correct_grid[0][0] = 9
print(correct_grid)
How the Example Works
Both rows change in the incorrect grid because the same inner list is repeated. The comprehension creates two separate inner lists.
Example Output
[[9, 0, 0], [9, 0, 0]]
[[9, 0, 0], [0, 0, 0]]
[[False, True], [False, False], [False, False]]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
grid = [[False for column in range(2)] for row in range(3)]
grid[0][1] = True
print(grid)
Important Behavior and Edge Cases
List repetition is safe for many immutable scalar values but hazardous for mutable nested values. Verify object identity when behavior is surprising.
Try It Yourself
Create a 3-by-2 grid with independent rows.
Common Beginner Mistakes
- List repetition is safe for many immutable scalar values but hazardous for mutable nested values. Verify object identity when behavior is surprising.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- Multiplying a list repeats references to its existing elements.
- Both rows change in the incorrect grid because the same inner list is repeated.
- List repetition is safe for many immutable scalar values but hazardous for mutable nested values.