Why does this iterative list-growing code give IndexError: list assignment index out of range?

Please consider the following code:

i = [1, 2, 3, 5, 8, 13]
j = []
k = 0

for l in i:
    j[k] = l
    k += 1

print j

The output (Python 2.6.6 on Win 7 32-bit) is:

> Traceback (most recent call last): 
>     j[k] = l IndexError: list assignment index out of range

I guess it’s something simple I don’t understand. Can someone clear it up?

9 Answers
9

Leave a Comment