I tried writing some code like:
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
But I get an error message that says IndexError: list assignment index out of range, referring to the j[k] = l line of code. Why does this occur? How can I fix it?
jis 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:
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:
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 (
Nonein the example below), and later, overwrite the values in specific positions:The thing to realise is that a
listobject will not allow you to assign a value to an index that doesn’t exist.