Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an item equals to one out of many elements in Python

Tags:

python

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?

like image 300
Flake Avatar asked Dec 13 '22 08:12

Flake


1 Answers

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.

like image 184
Duncan Avatar answered Apr 06 '23 00:04

Duncan