I need to create a nested list, four levels deep. On the fourth level, I need to systematically assign values. I get an index error, regardless of value assigned, when the fourth level is in the middle of its first loop, as you can see in the output below the code.
fourNest = [ [[[[[AA, BB, CC, DD]
for AA in range(2)]
for BB in range(3)]
for CC in range(4)]
for DD in range(5)]]
print fourNest #this prints as expected and assignments work manually
for AA in range(2):
print "AA = ", AA
for BB in range(3):
print " BB = ", BB
for CC in range(4):
print " CC = ", CC
for DD in range(5):
fourNest[AA][BB][CC][DD] = 1
print " DD = ", DD," ", fourNest[AA][BB][CC][DD]
AA = 0 BB = 0 CC = 0 DD = 0 1 DD = 1 1 DD = 2 1
Traceback (most recent call last):
File "C:/Python27/forListCreateTest", line 21, in <module>
fourNest[AA][BB][CC][DD] = 1
IndexError: list assignment index out of range
2 Answers 2
The order of the loops in the LC needs to be reversed. You also have one level of extra brackets in there
fourNest = [[[[[AA, BB, CC, DD]
for DD in range(5)]
for CC in range(4)]
for BB in range(3)]
for AA in range(2)]
-
Thank you everyone for your answers and comments, and so fast! This was my first post here, what a great site!Luke– Luke08/10/2011 17:33:53Commented Aug 10, 2011 at 17:33
>>> fourNest[0][0][0][0]
[[0, 0, 0, 0], [1, 0, 0, 0]]
>>> fourNest[0][0][0]
[[[0, 0, 0, 0], [1, 0, 0, 0]], [[0, 1, 0, 0], [1, 1, 0, 0]], [[0, 2, 0, 0], [1, 2, 0, 0]]]
...
So the innermost lists (not considering the generated 4 numbers) have two elements, the next outer 3 and so on..
You try to use it like it were the reverse...
Explore related questions
See similar questions with these tags.
[AA, BB, CC, DD]
in the comprehension with simply 1, and get rid of the final set of nested for loops. (BTW, in cases like this, I wish the Python standard library had an "autogrowing list" container class, similar in spirit to collections.defaultdict; then, together with itertools.product, one could code this in two lines.)