Lists
How to find the index of an item in a list in Python
Quick answer
Use list.index() or enumerate() to find the index of an item in a list in Python, e.g. my_list.index(item)
my_list = [1, 2, 3]
item = 2
try:
index = my_list.index(item)
print(f'Item {item} found at index {index}')
except ValueError:
print(f'Item {item} not found in list')The snippet uses the list.index() method to find the index of a given item in a list. This approach wins because it is straightforward and efficient. However, it raises a ValueError if the item is not found, so we use a try-except block to handle this case. The enumerate() function can also be used to iterate over the list with indices.
Variations
Alternate approach
for i, x in enumerate(my_list):
if x == item:
print(f'Item {item} found at index {i}')uses enumerate()
Safer variant
index = next((i for i, x in enumerate(my_list) if x == item), None)
if index is not None:
print(f'Item {item} found at index {index}')avoids ValueError
Related pattern
my_dict = {1: 'a', 2: 'b'}
item = 2
if item in my_dict:
print(f'Item {item} found in dict')finding key in dict
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.