Python Indexerror: list assignment index out of range Solution (original) (raw)

Last Updated : 14 Jan, 2025

In Python, the IndexError: list assignment index out of range occurs when we try to assign a value to an index that exceeds the current bounds of the list. Since lists are dynamically sized and zero-indexed, it’s important to ensure the index exists within the list’s range before modifying it. Understanding and handling this error properly will help us avoid issues when working with lists.

Python `

li= ['Apple', 'Banana', 'Guava']

to check type of fruits

print("Type is", type(li))
li[5] = 'Mango'

`

**Output:

Traceback (most recent call last):
File "/example.py", line 3, in
li[5]='Mango'
IndexError: list assignment index out of range

So, as we can see in the above example, we get an error when we try to modify an index that is not present in the list of fruits.

Let’s explore how to handle the IndexError: list assignment index out of range in Python.

Using append()

To avoid indexerror, we can use append() to safely add elements to a list without worrying about exceeding the list’s index range. append() method automatically adds the item to the end of the list, ensuring that no index errors occur.

Python `

li = ['Apple', 'Banana', 'Guava'] li.append("Mango") # Safely add to the end of the list print(li)

`

Output

['Apple', 'Banana', 'Guava', 'Mango']

**Explanation:

Using index()

If we need to insert an element at a specific position, insert() can be used without worrying about index out of range, as it handles out-of-range indices by adding elements in place.

Python `

li = ['Apple', 'Banana', 'Guava']

li.insert(1, "Mango") print(li)

`

Output

['Apple', 'Mango', 'Banana', 'Guava']

**Explanation:

Using try-except

To handle indexerror without crashing the program, we can use a try-except block. This allows us to catch the error and implement fallback behavior, such as safely adding the new element to the list.

Python `

li = ['Apple', 'Banana', 'Guava'] index = 5

try: li[index] = "Mango" except IndexError: # Handle the error by appending or resizing the list li.append("Mango") # Adding it safely print(li)

`

Output

['Apple', 'Banana', 'Guava', 'Mango']

**Explanation: