Get an Index of an Element in a List in Python
Problem
- You need the zero-based position of an element in a Python list.
- You want the first match, all matches, or the index while looping.
Solutions
Python Get an Index of Item in list
Use list.index(x[, start[, end]]) to return the first match. It raises ValueError if not found.
items = ["a", "b", "c", "b"]
i = items.index("b") # 1
j = items.index("b", 2) # 3 (search from index 2)
Get Index of Element in list: Python Error Handling
Handle “not found” errors explicitly with try/except, or return a default with next(...):
items = ["a", "b", "c"]
try:
i = items.index("z")
except ValueError:
i = -1
Python Enumerate Examples
enumerate() is concise and usually faster than manual indexing because it is implemented in C. If you searched for “for enumerate python,” this is the idiom you want for indexing while looping.
letters = ["a", "b", "c"]
for i, ch in enumerate(letters):
print(i, ch)
NOTE:
enumerate()returns anintindex, and the value at that specific index position. Read Python’s own documentation for more details.
Here’s another example with enumerate() that gets an index int type as a one-liner:
items = ["a", "b", "c"]
i = next((k for k, v in enumerate(items) if v == "z"), -1) # -1 if absent
Index Enumerate in Python
Use enumerate() to scan once and get (index, value) pairs. This is the common “python for enumerate index” pattern. It gives both the index and the value (“python for index value in enumerate”) in a single pass.
data = ["x", "y", "x", "z"]
target = "x"
first_idx = next((i for i, v in enumerate(data) if v == target), -1) # 0
all_idx = [i for i, v in enumerate(data) if v == target] # [0, 2]
Python for Loop with Index
This is a “for loop in python with index” using enumerate(). Use it when you need a “for loop python index” that also exposes the item.
colors = ["red", "green", "blue"]
for i, c in enumerate(colors):
print(i, c) # 0 red, 1 green, 2 blue
Python for Loop with Range Example
Use range(len(seq)) if you only need indices or plan to mutate in place. It is more verbose than enumerate() but still valid.
nums = [10, 20, 30, 20]
target = 20
for i in range(len(nums)):
if nums[i] == target:
print("found at", i) # 1 then 3
Collect all indices with a comprehension.
nums = [1, 2, 3, 2, 4, 2]
matches = [i for i in range(len(nums)) if nums[i] == 2]
print(matches) # [1, 3, 5]
Python Iterate list with Index
enumerate(seq, start=1) is useful when you want 1-based positions while iterating.
names = ["alice", "bob", "carol"]
for pos, name in enumerate(names, start=1):
print(pos, name) # 1 alice, 2 bob, 3 carol
for Loops Example in Python
Find and print every index where a target occurs. Here’s a for loop in Python with an index:
data = [5, 8, 13, 8, 21]
target = 8
for i, v in enumerate(data):
if v == target:
print(i) # 1 then 3
Another Python for Loop Example
This example uses the break keyword to “short-circuit” the function once it finds its target:
data = ["a", "b", "c", "b"]
target = "b"
idx = -1
for i, v in enumerate(data):
if v == target:
idx = i
break
print(idx) # 1
It exits after the first match to get a single index quickly.
Python: Index of Element with List (typing)
Wrap the pattern in a reusable helper that returns -1 when missing.
This example uses the List type, found in the ‘typing’ library, to add some static typing support for your get-index-of-element-in-list Python code:
from typing import List, Any
def find_index(seq: List[Any], target: Any) -> int:
return next((i for i, v in enumerate(seq) if v == target), -1)
print(find_index(["cat", "dog", "fish"], "dog")) # 1
print(find_index(["cat", "dog", "fish"], "cow")) # -1
For Loop in Python with Index
You can combine mutation and indexing. This shows replacing a matched item in place.
nums = [3, 4, 5, 4]
target = 4
for i in range(len(nums)):
if nums[i] == target:
nums[i] = 99
# nums is now [3, 99, 5, 99]
Python for Loop with range
- Use
range(len(my_list))when you need indices explicitly. - Combine
rangewith a condition to get the index of a matching element.
This is less Pythonic than enumerate(), but sometimes useful if you need to mutate items in place or only care about the index:
nums = [10, 20, 30, 20]
target = 20
for i in range(len(nums)):
if nums[i] == target:
print("found at", i) # prints 1 and 3
You can also collect all indices this way:
nums = [1, 2, 3, 2, 4, 2]
target = 2
matches = [i for i in range(len(nums)) if nums[i] == target]
print(matches) # [1, 3, 5]
Python: Find Index of All Occurrences in List
Use a comprehension with enumerate() to collect every matching index.
items = ["x", "y", "x", "z", "x"]
target = "x"
indices = [i for i, v in enumerate(items) if v == target]
print(indices) # [0, 2, 4]
For large numeric arrays, numpy.where is efficient:
import numpy as np
arr = np.array([10, 20, 30, 20])
indices = np.where(arr == 20)[0].tolist()
print(indices) # [1, 3]
Things to Consider
list.index()returns the first match only.- It is
O(n); large lists mean linear scans. ValueErroris raised if the element is absent.- Search can be narrowed with
start/endbounds. - For frequent lookups, prebuild a dict
{value: first_index}. - Lists do not have
rindex; use reversed search or comprehension if you need the last match.
Enumerate vs Range in Python
- Both
enumerate()andrange(len(seq))let you access indices, butenumerate()also gives you the value directly. - When your goal is to get the index of an item in a list,
enumerate()avoids an extra lookup (seq[i]) and is more readable. range(len(seq))is still valid, especially if you only care about indices or need to mutate the list in place.
items = ["a", "b", "c"]
target = "b"
# Using enumerate to find the index
idx = next((i for i, v in enumerate(items) if v == target), -1)
# Using range(len(...)) to find the index
idx2 = next((i for i in range(len(items)) if items[i] == target), -1)
Enumerate vs For Loop in Python
- A plain
for item in seq:loop won’t give you the index. - If you need both the index and the value (to get the index of a list element while scanning),
enumerate()is the natural fit. - The plain loop is best when the index is irrelevant, but
enumerate()is the right tool when your problem is “which position is this item at?”
colors = ["red", "green", "blue"]
target = "green"
# Plain for loop (no index)
for c in colors:
if c == target:
print("Found target!") # No index available
# Enumerate for loop (with index)
for i, c in enumerate(colors):
if c == target:
print("Found at index", i) # 1
Enumerate Function in Python
A reusable helper can wrap enumerate() to return the index of the first match, or -1 if not found.
from typing import List, Any
def find_index(lst: List[Any], target: Any) -> int:
for i, v in enumerate(lst):
if v == target:
return i
return -1
# Example
data = ["apple", "banana", "cherry"]
print(find_index(data, "banana")) # 1
print(find_index(data, "pear")) # -1
The above
find_index()works as a reusable function so you can write DRY code.
Gotchas
list.index()only returns the first match, not all.- Catch
ValueErroror use a safe pattern (likenext(...)) to avoid crashes if an item is missing. - Avoid
range(len(lst))unless you truly need raw indices;enumerate()is clearer. - Do not assign variables named after built-in types (
list,dict,str, etc.) — it overwrites them and breaks built-in functionality. - Mixed-type lists (
[None, True, "foo", 123]) can lead to unexpected comparisons or type errors in some operations; always confirm what kind of equality check makes sense for your case.
Sources
- Official Documentation (list.index)
- Official Documentation (enumerate)
- Relevant StackOverflow answer
Further Investigation
- Use
bisectfor positions in sorted lists. - Consider
numpy.wherefor vectorized index operations on arrays. - Build reverse maps (value → indices) when scanning once, querying many times.
- Related guide or blog post
TL;DR
Use list.index(x) for the first match; enumerate() for index during loops; comprehensions for all matches:
# First match (or -1 if not found)
i = next((k for k, v in enumerate(lst) if v == x), -1)
You can turn this one-liner into a reusable function:
from typing import Any, List
def index_of(lst: List[Any], target: Any) -> int:
"""Return the index of target in lst, or -1 if not found."""
return next((i for i, v in enumerate(lst) if v == target), -1)
# Examples
print(index_of([10, 20, 30], 20)) # 1
print(index_of([10, 20, 30], 99)) # -1
try except catch Python Example
If you really need explicit error handling, then this other Python function example may work for you:
from typing import Any, List
def index_of(lst: List[Any], target: Any) -> int:
try:
return next((i for i, v in enumerate(lst) if v == target), -1)
except TypeError as err:
print("Error:", err)
return -1
Only useful if you expect weird cases (like lst not being iterable).