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
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