Search code examples
pythonlistnested-loopsnested-lists

Why am I getting "list assignment index out of range" error?


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

Solution

  • 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 Nones. 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.