🐍 2D Lists
Good to know
2D Lists are simply lists that contain other lists. Useful for grids, tables, matrices, or game boards.
Creating a 2D List
number_grid = [
[1, 2, 3], # row 0
[4, 5, 6], # row 1
[7, 8, 9] # row 2
]Building a 2D List Dynamically
col = []
for _ in range(3):
col.append(0)
grid = []
for _ in range(3):
grid.append(col.copy()) # use copy() to avoid shared referencesManipulate 2D List
Accessing Values
Use two indexes: [row][column].
number_grid[2][1] # → 8
# row 2: [7, 8, 9]
# column 1 in that row → 8Important: Avoid Shared Lists
a = [0,0,0]
bad_grid = [a] * 3 # ❌ all rows reference the SAME list
bad_grid[0][1] = 9
print(bad_grid)
# → [[0,9,0], [0,9,0], [0,9,0]]Always use copy() or list comprehension:
good_grid = [a.copy() for _ in range(3)] # ✔ independent rowsLooping Through a 2D List
Find here how to loop through a dictionary: Looping Through a 2D List