Python / Pygame grid design fails for append "index out of range"

Viewed 36

I am trying to create a grid starting at row 2, column 13. The grid will end at row 12, column 25. However I keep getting a "list index out of range" error on the append(0)line. Obviously I am not understanding how the append works.

grid = []
for row in range(2,12):
    # Add an empty array that will hold each cell
    # in this row
    grid.append([])
    for column in range(13,25):
        grid[row].append(0)  # Append a cell
1 Answers

The indices of lists always start at 0. range(2, 12) creates the numbers from 2 to 12. However the indices of the list grid still start at 0. You need to subtract 2 from row:

grid[row].append(0) # Append a cell

grid[row-2].append(0)  # Append a cell

Get the index of the next row with len(grid), before appending a new row:

grid = []
for row in range(2, 12):
    
    index_of_next_row = len(grid)
    grid.append([])
    
    for column in range(13, 25):
        grid[index_of_next_row].append(0)

Alternatively, you can create a roe and append it to the grid when the row is finished:

grid = []
for row in range(2, 12):
    
    new_row = []
    
    for column in range(13, 25):
        new_row.append(0)

    grid.append(new_row)

Or even shorter:

grid = [[0 for cell in range(13, 25)] for row in range(2, 12)]
Related