Python IndexError: list index out of range














































Python IndexError: list index out of range



python IndexError: list index out of range

List:

In python, lists are mutable(objects inside the list can be changed).  It can be created by placing items inside square brackets[ ], which are separated by commas. Each element in the list is accessed using index in square brackets where index starts from '0'. It can have any number of items with different types i.e., int, float, string etc.,

Creating the list:


list=[]
list=[1,2,3]
list=['abc',234, 13.45]

You can create list inside the list as:

list=['abc',['a','b',1], 12.87]

Accessing the list:

We can access the list in different ways.

  • Through indexing
  • Through negative indexing
  • Slicing
Let's consider the example:



ERROR:


While accessing the list, when we try to access the list elements with the index which is not 
present, leads to 'Index Error'.



In the above example, the length of 'list' is 3 and  list 'index' ranges from 0 to 2.

When trying to access list with index '3' results in Index Error: list index out of range.

Index Error: list index out of range can be handled by using try and except method


Comments