I want to create a 2D grid with for loop in python. I can do simple code like this:
cols = 10
rows = 10
grid = [[0 for x in range(cols)] for y in range(rows)]
print(grid)
But when I try to loop through i in rows and then j in columns, it shows error: list index out of range. Not sure where went wrong with my coding?
rows = 10
cols = 10
i = 0
for i in range(rows):
for j in range(cols):
grid[i].append([j])
i += 1
You need to create an empty sublist before you use something like grid[i].append(). Because initially there is nothing in the list and you refer to something that is not available. Hence, your error. :(
You could instead create a sublist in each outer iteration and append 0 to previous sublist in the inner iteration:
cols = 10
rows = 10
grid = []
for _ in range(rows):
grid.append([])
for _ in range(cols):
grid[-1].append(0)
print(grid)
# [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
grid = [[0 for _ in range(cols)] for _ in range(rows)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With