I want to check if an item from a list equals to any one element out of a given set of n elements, if yes, do some thing.
For example, the most intuitive but of course cumbersome and ugly way is:
for item in List:
if (item == element1) or (item == element2) or ... or (item == elementn):
do something
What are the better ways to check?
You use the in
operator:
elements = set((element1, element2, ..., elementn))
...
if item in elements:
do something
Use either a set or a tuple for the elements: a set is faster for lookups but requires the elements be hashable. A tuple is lighter weight for a few elements but gets slower if there are more than a few elements.
Also, unless the elements vary through your loop you should initialise the collection outside the loop to avoid the overhead of creating the set/tuple every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With