2

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.

3
  • you are working with list objects, not arrays. Commented Nov 14, 2017 at 18:51
  • Anyway, you've got length and breadth reversed. When you first index into sheet, there are breadth many elements. When you index into one of the sublists in sheet, there are length many elements. Commented Nov 14, 2017 at 18:53
  • Would you mind accepting an answer, if it helped you solve the problem? Commented May 16, 2018 at 21:44

2 Answers 2

1

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.]])
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.