gokyori
gokyori

Reputation: 367

list assignment index out of range for 2d array error

I looked into answers regarding similar questions but couldn't figure out my problem. I am newbie to python please help.

length = 13
breadth = 24
sheet = [ [ 0 for y in range( length ) ] for x in range( breadth ) ]
sheet[length-2][breadth-3] = 1

The above code gives me list assignment index out of range error.

Upvotes: 2

Views: 461

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20434

You have either the list-comprehension the wrong way around, it should be:

length = 13
breadth = 24
sheet = [ [ 0 for x in range( breadth ) ] for y in range( length ) ]
sheet[length-2][breadth-3] = 1

Or you have the indexing of the sheet list the wrong way around, it should be:

length = 13
breadth = 24
sheet = [ [ 0 for x in range( length ) ] for y in range( breadth ) ]
sheet[breadth-2][length-3] = 1

Both corrections will work fine, but it depends on what you are defining breadth and width to be.


In the first example, the list looks like:

  #breadth --->
[[0,0 ....  0,0],  #width |
 ...               #      |
 [0,0 ....  0,0],  #      \/
]

there are width rows of size breadth

In the second:

  #width --->
[[0,0 ....  0,0],  #breadth |
 ...               #        |
 [0,0 ....  0,0],  #        \/
]

there are breadth rows of size width

Upvotes: 1

Daniel Lenz
Daniel Lenz

Reputation: 3877

You have the axes mixed up, try using

sheet[breadth-3][length-2] = 1

Alternatively, you could use numpy to do this more elegantly:

import numpy as np

breadth = 5
length = 3

sheet = np.zeros(shape=(breadth, length))
sheet[breadth-3, length-2] = 1

sheet.shape
>>> (5, 3)

sheet
>>> array([[ 0.,  0.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  1.,  0.],
   [ 0.,  0.,  0.],
   [ 0.,  0.,  0.]])

Upvotes: 1

Related Questions