0

My program uses the code below to insert an object named Field to a multidimensional array that is created on the fly (at least I thought it would be created):

for x in range(self.width):
    for y in range(self.height):
            self.board_fields[x][y] = Field()

So board_fields wasn't created on the fly and I got the error:

AttributeError: 'Board' object has no attribute 'board_fields'

How should I define the multidimensional array before putting values into it?

1
  • Are you sure that the above mentioned code got executed? Because, the error makes me feel that, python doesn't even know what board_fields is. Commented Jul 2, 2013 at 12:54

2 Answers 2

2
self.board_fields = [[Field() for j in range(self.height)] for i in range(self.width)]
Sign up to request clarification or add additional context in comments.

2 Comments

Upvoted :) Is there any other way in which I can create multi-dimensional arrays, with just default python libraries?
Aside from list comprehensions (which I used above), you could use nested for loops (like @astex's solution). For an arbitrary number of dimensions, you could write a recursive function that accepts a list of dimensions.
1

These aren't really arrays in the classical sense, but lists of lists. While this is a semantic difference in some contexts, here it affects where within the lists assignment can be made. The append statement allocates additional memory to the list and assigns its argument to that new 'slot'.

self.board_fields = []
for x in range( self.width ):
    board_fields_sub = []
    for y in range( self.height ):
        board_fields_sub.append( Field() )
    self.board_fields.append( board_fields_sub )

2 Comments

if you mean to add the line self.board_fields =[] then I get the error self.board_fields[x][y] = Field() IndexError: list index out of range
@Tom No, that’s not enough. An empty list has still no items so indexing will fail. astex creates empty lists and then appends the items to that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.