Python List | index method
Start your free 7-days trial now!
Python's list.index(~)
method returns the position of the first occurrence of the specified element in a list.
Parameters
1. x
| any
The element to search for in the list.
2. start
| number
| optional
The index position from which to start the search (inclusive). Defaults to 0.
3. end
| number
| optional
The index position at which to end the search (exclusive). Defaults to length of list (i.e. last index position in list + 1).
Return value
Index position of the first occurrence of the element x
in the list.
Examples
Basic usage
To return the index position of the first occurrence of 'koala'
in animals
list:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']animals.index('koala')
0
Note that index positions in Python start at 0 not 1. Therefore we see return value of 0
as 'koala'
is the first element in list animals
.
ValueError
To return the index position of the first occurrence of 'panda'
in animals
list:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']animals.index('panda')
ValueError: 'panda' is not in list
As 'panda'
does not exist in the list animals
, a ValueError
is raised:
Start parameter
To start the search for 'koala'
at index position 1
of animals
:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']animals.index('koala', 1)
4
4
is returned as 'koala'
first occurs at index position 4
(5th element) after index position 1
in animals
.
End parameter
To end the search for 'cat'
at the third to last element in animals
:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']animals.index('cat', 0, -2)
ValueError: 'cat' is not in list
The search excludes the element at index position end
(in this case -2
(second to last element) which is occupied by element 'cat'
). As a result the search ends after checking element at index position -3
('dog'
), which is why a ValueError
is thrown.