Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D grid using for loop in Python

Tags:

python

arrays

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
like image 860
user10381476 Avatar asked Aug 26 '26 08:08

user10381476


1 Answers

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]]


Combining the whole to one line:
grid = [[0 for _ in range(cols)] for _ in range(rows)]
like image 73
Austin Avatar answered Aug 28 '26 21:08

Austin