1

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
1
  • 1+ nice puzzle... (i like gnibbler's answer's best: as he points out, your code as not one, but rather two errors). Also, FWIW, you'll get the same final result if you replace the inner [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.) Commented Aug 10, 2011 at 1:35

2 Answers 2

1

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

1 Comment

Thank you everyone for your answers and comments, and so fast! This was my first post here, what a great site!
0
>>> 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...

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.