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
[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.)