user1880866
user1880866

Reputation: 39

Python: Index Error for 3D list

I've never worked with 2D or 3D arrays before but i'm trying to make a maze. In my snippet, squares is a list with each instance of a cell (so in a 3x4 maze, there would be 12 instances in squares) I am then trying to append to row, a list of all the squares in a row, so row[0] would contain the first four square instances, row[1] would be the next four, etc. the row[x].append(squares[y+z]) throws the IndexError, i'm guessing it's the row[x] part, but i'm not sure what to do to fix it. I tried using extend instead of append.

numberOfRows = 3
numberOfColumns = 4
z = 0

for x in range(numberOfRows):
    for y in range(numberOfColumns):
        row[x].append(squares[y+z])
    z += 4

Upvotes: 1

Views: 201

Answers (2)

mmgp
mmgp

Reputation: 19241

If I'm guessing it right, you want:

numberOfRows = 3
numberOfColumns = 4
z = 0

squares = range(numberOfRows * numberOfColumns)

row = [[] for _ in xrange(numberOfRows)]
for x in range(numberOfRows):
    for y in range(numberOfColumns):
        row[x].append(squares[y+z])
    z += 4

print row

i.e., you were only missing the row definition.

EDIT:

After reading OP's comments, it seems that considering the following alternative is worth for the situation:

row = []
for x in range(numberOfRows):
    row.append([squares[y+z] for y in range(numberOfColumns)])
    z += numberOfColumns

So you don't create all the lists in row beforehand.

Upvotes: 1

Aesthete
Aesthete

Reputation: 18848

This can be simplified to the following:

>>> [squares[i:i+numberOfColumns] for i in range(0, len(squares), numberOfColumns)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

Upvotes: 0

Related Questions