The Python Oracle

Why does this iterative list-growing code give IndexError: list assignment index out of range? How can I repeatedly add (append) elements to a list?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Question
00:40 Accepted answer (Score 391)
01:37 Answer 2 (Score 63)
01:50 Answer 3 (Score 29)
02:05 Answer 4 (Score 18)
02:22 Thank you

--

Full question
https://stackoverflow.com/questions/5653...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #exception

#avk47



ACCEPTED ANSWER

Score 402


j is an empty list, but you're attempting to write to element [0] in the first iteration, which doesn't exist yet.

Try the following instead, to add a new element to the end of the list:

for l in i:
    j.append(l)

Of course, you'd never do this in practice if all you wanted to do was to copy an existing list. You'd just do:

j = list(i)

Alternatively, if you wanted to use the Python list like an array in other languages, then you could pre-create a list with its elements set to a null value (None in the example below), and later, overwrite the values in specific positions:

i = [1, 2, 3, 5, 8, 13]
j = [None] * len(i)
#j == [None, None, None, None, None, None]
k = 0

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

The thing to realise is that a list object will not allow you to assign a value to an index that doesn't exist.




ANSWER 2

Score 67


Your other option is to initialize j:

j = [None] * len(i)



ANSWER 3

Score 30


Do j.append(l) instead of j[k] = l and avoid k at all.




ANSWER 4

Score 11


j.append(l)

Also avoid using lower-case "L's" because it is easy for them to be confused with 1's