Skip to content
Related Articles

Related Articles

Python Indexerror: list assignment index out of range Solution

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 04 Jan, 2022

In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range.  

Python Indexerror: list assignment index out of range Example

If ‘fruits’ is a list, fruits=[‘Apple’,’ Banana’,’ Guava’]and you try to modify fruits[5] then you will get an index error since the length of fruits list=3 which is less than index asked to modify for which is 5.

Python3




# list of fruits
fruits = ['Apple', 'Banana', 'Guava']  
  
# to check type of fruits
print("Type is", type(fruits))  
fruits[5] = 'Mango'


Output:

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

So, as you 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.

Python Indexerror: list assignment index out of range Solution

Method 1: Using insert() function

The insert(index, element) function takes two arguments, index and element, and adds a new element at the specified index.

Let’s see how you can add Mango to the list of fruits on index 1.

Python3




fruits = ['Apple', 'Banana', 'Guava']
print("Original list:", fruits)
  
fruits.insert(1, "Mango")
print("Modified list:", fruits)


Output:

Original list: ['Apple', 'Banana', 'Guava']
Modified list: ['Apple', 'Mango', 'Banana', 'Guava']

It is necessary to specify the index in the insert(index, element) function, otherwise, you will an error that the insert(index, element) function needed two arguments.

Method 2: Using append()

The append(element) function takes one argument element and adds a new element at the end of the list.

Let’s see how you can add Mango to the end of the list using the append(element) function.

Python3




fruits = ['Apple', 'Banana', 'Guava']
print("Original list:", fruits)
  
fruits.append("Mango")
print("Modified list:", fruits)


Output:

Original list: ['Apple', 'Banana', 'Guava']
Modified list: ['Apple', 'Banana', 'Guava', 'Mango']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!