List index() method Python

The list index() method of Python searches for a value in the list object.If the value is found the index of the value is returned,note the index count begins form 0.

ls=[12 ,3, 4 , '12345' , 'Text' , 23.45 , (23 ,45) , [23] ]
ls.index( 23.45 )
5
>>> ls.index( [23] )
7
>>> ls.index( 1234 )
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    ls.index( 1234 )
ValueError: 1234 is not in list

When we try to locate the index of 1234 in ‘ls’ the function return to us an error message since it cannot be found and also the function raises a ‘ValueError’ exception.Raising this exception simply means the argument passed to the function does not make sense and cannot be made used by the function.More about ValueError here.


Using the index( x, start , end ) function

The index() method can also accept three arguments.When passing three arguments:
 
i)The first argument is the value whose index is to be located in the list object.
 
ii)The second argument represent the index of the starting point in the list object were the search for the value(the first argument) should begin.
 
iii)The third argument signify the end point of the sequence within which the search for the value(the first argument) should be limited.
 
By using the extra two arguments we can limit the search for the value in the list object sequence.

>>> ls=[12 ,3, 4 , '12345' , 'Text' , 23.45 , (23 ,45) , [23] ]
>>>  ls.index( 4 , 0, 3) #searches for 4 within 0 to 3 index 
2
>>> ls.index( 4 , 3, 6) #search for 4 within 3rd and 6th index
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    ls.index( 4 , 3, 6)
ValueError: 4 is not in list

When we called ‘ls.index( 4 , 3, 6)’ we get an error message stating that ‘4 is not in list’.This is because we have limited the search for 4 only within 3rd to 6th index in the list object and since 4 is found in the 2nd index the function could not locate the index of 4.Another code example is given below.

>>> li=[232 , 09.34 , (34,) , 34 , 'New' , [23] , '000' , 1]
>>> li.index( (34,) , 2 , 5 )
2
>>> li.index( 'New' , 0 , 3 )
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    li.index( 'New' , 0 , 3 )
ValueError: 'New' is not in list
>>> li.index( [23] , 0 , len(li) ) #same as li.index( [23] , 0 , len(li) )
5


Leave a Reply

Your email address will not be published. Required fields are marked *