Python: finding an element in a list
To check if an element's present in a list, use in
:
If you want to know where the element is chillin' on the list, utilize index()
:
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:
In the realm of custom objects, redefine __eq__
method for index()
to recognize them:
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:
Just ensure the library has only unique books to avoid the librarian bringing duplicates:
Using the power of numpy
Your list is big and consists of numbers? Use numpy.where
:
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:
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:
It's efficient like having a list of seating arrangements, without bothering anyone!
Was this article helpful?