0
0
PythonHow-ToBeginner · 3 min read

Find All Indices of Element in List Python: Simple Guide

To find all indices of an element in a Python list, use a list comprehension with enumerate() to check each item and collect matching indices. For example, [i for i, x in enumerate(your_list) if x == element] returns all positions of element.
📐

Syntax

The common syntax to find all indices of an element in a list uses enumerate() inside a list comprehension:

  • enumerate(your_list) gives pairs of index and value.
  • The list comprehension filters values equal to the target element.
  • It collects the matching indices into a new list.
python
indices = [i for i, x in enumerate(your_list) if x == element]
💻

Example

This example shows how to find all indices of the number 3 in a list.

python
your_list = [1, 3, 7, 3, 2, 3, 4]
element = 3
indices = [i for i, x in enumerate(your_list) if x == element]
print(indices)
Output
[1, 3, 5]
⚠️

Common Pitfalls

One common mistake is using list.index() which only returns the first occurrence and raises a ValueError if the element is not found. Another is forgetting to use enumerate(), which means you only get values, not indices.

Always use enumerate() to get indices and handle cases where the element might not be in the list.

python
wrong = your_list.index(element)  # Only first index, error if not found

# Correct way:
indices = [i for i, x in enumerate(your_list) if x == element]
📊

Quick Reference

  • Use: [i for i, x in enumerate(list) if x == element]
  • Returns: List of all indices where element appears
  • Works for: Any list with repeated elements
  • Raises no error: If element not found, returns empty list

Key Takeaways

Use list comprehension with enumerate() to find all indices of an element in a list.
list.index() only finds the first occurrence and can cause errors if element is missing.
The method returns an empty list if the element is not found, avoiding errors.
This approach works well for lists with repeated elements.
Always test your code with lists that do and do not contain the element.