Reputation: 2488
I keep getting the same error:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
IndexError: list assignment index out of range
What's wrong with the following code?
myList = [([None] * 8) for x in range(16)]
for i in range(0,7):
for j in range(0,15):
myList[i][j] = 2 * i
Upvotes: 1
Views: 615
Reputation: 239443
The list comprehension
myList = [([None] * 8) for x in range(16)]
can be understood like this
mylist = []
for x in range(16):
mylist.append([None] * 8)
So, you are creating a list of 16 lists, each contains 8 None
s. But with the loops
for i in range(0,7):
for j in range(0,15):
you are trying to access 15 elements from the first 7 lists. That is why it is failing. Instead, you might want to do
for i in range(16):
for j in range(8):
...
Actually you can do the same in list comprehension, like this
[[2 * i for j in range(8)] for i in range(16)]
Demo:
>>> from pprint import pprint
>>> pprint([[2 * i for j in range(8)] for i in range(16)])
[[0, 0, 0, 0, 0, 0, 0, 0],
[2, 2, 2, 2, 2, 2, 2, 2],
[4, 4, 4, 4, 4, 4, 4, 4],
[6, 6, 6, 6, 6, 6, 6, 6],
[8, 8, 8, 8, 8, 8, 8, 8],
[10, 10, 10, 10, 10, 10, 10, 10],
[12, 12, 12, 12, 12, 12, 12, 12],
[14, 14, 14, 14, 14, 14, 14, 14],
[16, 16, 16, 16, 16, 16, 16, 16],
[18, 18, 18, 18, 18, 18, 18, 18],
[20, 20, 20, 20, 20, 20, 20, 20],
[22, 22, 22, 22, 22, 22, 22, 22],
[24, 24, 24, 24, 24, 24, 24, 24],
[26, 26, 26, 26, 26, 26, 26, 26],
[28, 28, 28, 28, 28, 28, 28, 28],
[30, 30, 30, 30, 30, 30, 30, 30]]
Note: I have used 16
and 8
in the range
function because it, by default, starts from 0 and iterates till the parameter passed to it - 1. So, 0 to 15 and 0 to 8 respectively.
Upvotes: 1
Reputation: 1121524
You have your indices reversed; the outer list has 16 elements, but you are trying to index the inner list past the 8 elements that are there.
That's because your list comprehension built 16 lists of each 8 values, so len(myList)
is 16, and len(myList[0])
is 8.
Reverse the ranges:
for i in range(15):
for j in range(7):
myList[i][j] = 2 * i
or reverse the use of i
and j
when trying to index against myList
:
for i in range(7):
for j in range(15):
myList[j][i] = 2 * i
Note that the outer myList
is using j
now and each nested inner list is indexed with i
.
Both i
and j
omit the last element, if that wasn't intentional, use 8
and 16
rather than 7
and 15
.
Upvotes: 1