How to find all occurrences of an element in a list
Discover every occurrence of element
in lst
with this elegant construct:
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:
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:
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:
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.
Was this article helpful?