IndexError: list assignment index out of range | Python Examples

#JavaInspires


Hi Guys,

One type of error is common to see when you’re working with lists for the first time. Let’s say you have a list with three items, and you ask for the fourth item.

Here this error having message as "IndexError: list assignment index out of range" means that

we are trying to access an item to an index that does not exist. 

Means if our list is of size 5 and when we try to access 6th element we get this error.

Below code results this error 

#create a simple list contains country names
country_list = ['US','Canada','Mexico']
#print this list
print(country_list)
# Add new element
country_list[4] = 'UK'
#print this list
print(country_list)


['US', 'Canada', 'Mexico']
Traceback (most recent call last):
  File "E:\code\python\python_list.py", line 6, in <module>
    country_list[3] = 'UK'
IndexError: list assignment index out of range
[Finished in 0.1s]

Here, we are having a list of size 3 but we tried to assign new value at 5th position 
(country_list[4] = 'UK') which doesn't exist.


#JavaInspires

Post a Comment

Previous Post Next Post