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?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Why Does This Iterative List-Growing Code Give Indexerror: List Assignment Index Out Of Range? How C
00:33 Accepted Answer Score 399
01:32 Answer 2 Score 66
01:45 Answer 3 Score 30
01:59 Answer 4 Score 18
02:17 Answer 5 Score 11
02:31 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