How to Get Index/Position of Item in Python List
To get the position of an element in a Python list, use the index()
function. Pass .index()
after the list to evaluate and the value of the element to look for as the first argument.
Let's try this out with an example.
items = ['a','b','c']
pos = items.index('c')
print(pos)
2
Note - The behaviour of index()
is to return the position of the first item found only.
If the Value is Not in the List
If the value is not found in the list, index()
will throw a ValueError.
items = ['a','b','c']
pos = items.index('d')
print(pos)
ValueError: 'd' is not in list
To avoid this error, use index()
inside a Python try except
statement like this:
items = ['a','b','c']
try:
pos = items.index('d')
except:
pos = False
print(pos)
False
Find Position of Item Within an Index Range
The index()
function accepts two more arguments. The second is the index to begin searching from and the third is where to stop searching.
In the example below, if the value 'c'
is not found between index 0 and 1, False
will be returned.
items = ['a','b','c']
try:
pos = items.index('c', 0, 2)
except:
pos = False
print(pos)
False