Explain Codes LogoExplain Codes Logo

How to find all occurrences of an element in a list

python
list-comprehension
numpy
custom-functions
Alex KataevbyAlex Kataev·Feb 17, 2025
TLDR

Discover every occurrence of element in lst with this elegant construct:

indices = [i for i, v in enumerate(lst) if v == element]

This line elegantly iterates through each v (value) in lst with its corresponding index i, collecting i into indices if it matches element. An efficient way to pinpoint all instances where fishing hooks catch the element fish.

The what, when, and why: Alternate approaches

Hitting the gym with numpy: Big data workout

Behemoths called large datasets would benefit from the strength of NumPy:

import numpy as np lst_np = np.array(lst) # Push-ups before the real workout indices = np.where(lst_np == element)[0] # Lifting weights

Keep in mind the transformation from list to NumPy array—remember to factor this in when dealing with non-array datatypes, to avoid paying unnecessary conversion taxes.

Going minimalist: Custom loop functions

When the needle in the haystack is thin and rare, a custom function may be your best friend:

def find_indices(lst, element): indices = [] for i, v in enumerate(lst): if v == element: indices.append(i) # Adding friends to the party return indices indices = find_indices(lst, element) # Party call!

This function smartly side-steps creating a bloated intermediate list of tuples that list comprehension with enumerate might otherwise spawn.

Travel in style: more_itertools

For a more minimalist approach, look no further. more_itertools.locate is your private jet:

from more_itertools import locate indices = list(locate(lst, lambda x: x == element))

You might need to install this module with pip install more_itertools. Keeping your jet updated is essential for a smooth flight!

Unpacking the trade-offs

Quicksilver list comprehension

The initial list comprehension cheeses it by offering a memory-speed trade-off, storing locations on-the-go, usually beneficial for Python applications where memory isn't exactly gold-dust.

The Python numpy powerhouse

NumPy's np.where() becomes exceptionally handy when you want to blast through queries for different elements against the same list. Courtesy, numpy arrays optimized for such bulky operations.

Iterator at your service: more_itertools

Deploying more_itertools.locate is recommended when you need an iterator over the indices. This prevents your memory from drowning when nibbling on hulk-sized lists.

Diverse elements? Consider a custom function

In the spotlight, the custom function excels in lists with infrequent target elements. This chameleon subtly disguises its efficacy boosting ways when it comes to lists with varied elements.