|
| Home |
|---|
The IndexError: list assignment index out of range is another common error encountered when working with Python lists. This error occurs when a program tries to assign a value to an index that does not exist in the list.
Unlike accessing a list element, this error occurs when a program tries to assign a value to an index that is outside the current size of the list.
Python lists start indexing from 0. If a list contains three elements, the valid indexes are 0, 1, and 2.
numbers = [10,20,30]
print(numbers[0])
print(numbers[1])
print(numbers[2])
10
20
30
numbers = [10,20,30]
numbers[3] = 40
IndexError: list assignment index out of range
The list only has indexes 0, 1, and 2. Index 3 does not exist, so Python raises an error.
colors = ["red","green","blue"]
colors[5] = "yellow"
IndexError: list assignment index out of range
To add elements at the end of a list, use the
append() method instead of assigning
to a non-existing index.
numbers = [10,20,30]
numbers.append(40)
print(numbers)
[10, 20, 30, 40]
If you want to add an element at a specific position,
use the insert() method.
numbers = [10,20,30]
numbers.insert(1,15)
print(numbers)
[10, 15, 20, 30]
Another solution is to create a list with the required number of elements before assigning values.
numbers = [0,0,0,0]
numbers[3] = 40
print(numbers)
[0, 0, 0, 40]
This error can also occur inside loops if indexes go beyond the list size.
numbers = [1,2,3]
for i in range(5):
numbers[i] = i
IndexError: list assignment index out of range
numbers = [1,2,3]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print(numbers)
[2, 4, 6]
The IndexError: list assignment index out of range occurs when a program tries to assign a value to an index that does not exist in the list.
This error can be avoided by using methods such as
append() and insert(), or by
ensuring the list has enough elements before assignment.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net