Explain Codes LogoExplain Codes Logo

Python: finding an element in a list

python
list-comprehension
numpy
bisect
Nikita BarsukovbyNikita Barsukov·Mar 3, 2025
TLDR

To check if an element's present in a list, use in:

my_list = ['apple', 'banana', 'cherry'] print('banana' in my_list) # Output: True, "banana" indeed loves to hang out here

If you want to know where the element is chillin' on the list, utilize index():

print(my_list.index('banana')) # Output: 1, banana always chilling in the middle

Careful, it gets upset and raises a ValueError if the element wasn't invited to the list!

When element is playing hide-and-seek (non-existent elements)

Sometimes, elements like to play hide-and-seek. index() throws a fit (ValueError) when it can't find the naughty element:

try: print(my_list.index('kiwi')) # Who invited a kiwi to an apple-banana-cherry party? ValueError throws a party crasher out except ValueError: print("Element not found!")

In the realm of custom objects, redefine __eq__ method for index() to recognize them:

class Fruit: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name # Now the objects can wear name tags fruits = [Fruit('apple'), Fruit('banana')] print(fruits.index(Fruit('banana'))) # Output: 1, our banana has been found at 1, yay!

Quick search in a big library (finding elements with conditions)

List comprehension is like hiring a librarian who knows exactly where that specific book is:

even_numbers = [x for x in range(10) if x % 2 == 0] print(even_numbers) # Output: [0, 2, 4, 6, 8]

Just ensure the library has only unique books to avoid the librarian bringing duplicates:

unique_elements = ['apple', 'banana', 'cherry', 'date'] indexes = [i for i, item in enumerate(unique_elements) if 'a' in item] print(indexes) # Output: [0, 1, 3] "a" has a lot of fans!

Using the power of numpy

Your list is big and consists of numbers? Use numpy.where:

import numpy as np numbers = np.array([1, 2, 3, 4, 5]) indexes = np.where(numbers > 3) print(indexes) # Output: (array([3, 4]),)

You can specify custom comparison operators too. Now that's efficient hunting!

Searching the old school way (sorted lists)

Sorting lists: for a fast search, sorting helps:

import bisect sorted_list = sorted(['cherry', 'apple', 'banana']) index = bisect.bisect_left(sorted_list, 'banana') print(index) # Output: 1, banana slides into the middle as usual

Notice, bisect_left is pretty advanced. It looks for the insertion place to keep everything tidy.

Good old for-loop with enumerate

When both the guest (element) and its seat number (index) are required, go hand-in-hand with enumerate and a loop:

for index, element in enumerate(my_list): print(f"Element: {element}, Index: {index}")

It's efficient like having a list of seating arrangements, without bothering anyone!