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']
Python Indexerror: list assignment index out of range Solution
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.
Contact Us