Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What does IndexError list assignment index out of range mean?

The message “list assignment index out of range” tells us that we are trying to assign an item to an index that does not exist. In order to use indexing on a list, you need to initialize the list. If you try to assign an item into a list at an index position that does not exist, this error will be raised.

Why does Python say list index out of range?

The error “list index out of range” arises if you access invalid indices in your Python list. For example, if you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.

How do you assign a list in Python?

To initialize a list in Python assign one with square brackets, initialize with the list() function, create an empty list with multiplication, or use a list comprehension. The most common way to declare a list in Python is to use square brackets.


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.


Your other option is to initialize j:

j = [None] * len(i)

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


You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]

j.append(l)

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


I think the Python method insert is what you're looking for:

Inserts element x at position i. list.insert(i,x)

array = [1,2,3,4,5]
# array.insert(index, element)
array.insert(1,20)

print(array)

# prints [1,20,2,3,4,5]