Python traps · Python

Python: I changed 1 cell and 3 changed?!PRO

Watch the video

[[0]*3]*3 makes three pointers to the SAME row. Build each row separately.

# I changed 1 cell and 3 changed ?! — [[0]*3]*3 makes three pointers to the SAME row.
grid = [[0] * 3] * 3
grid[0][0] = 9
for row in grid:
    print(row)          # 9 in EVERY row ?!

print("same row object?", grid[0] is grid[1])   # True

# Fix: build each row separately
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 9
for row in grid:
    print(row)          # just one 9 ✓
Open code P5 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code P5 in Code Library.