How to check if a variable is the same as at least one of two other variables? [duplicate]

StackOverflow https://stackoverflow.com/questions/23496860

  •  16-07-2023
  •  | 
  •  

Вопрос

I have a variable, and want to check if it matches at least one of the other two variables.

Clearly I can do:

if a == b or a == c:

But I want to know if there is any shorter way, something like:

if a == (b or c):

How to test if a variable is the same as - at least - one of the others?

Это было полезно?

Решение

For that use in:

if a in (b, c):

Testing for membership in a tuple has an average case of O(n) time complexity. If you have a large collection of values and are performing many membership tests on the same collection of values, it may be worth creating a set for speed:

x = set((b,c,d,e,f,g,h,i,j,k,l,...))
if a in x:
    ...
if y in x:
    ...    

Once it has been constructed, testing for membership in the set has an average case of O(1) time complexity, so it is potentially faster in the long run.

Or, you can also do:

if any(a == i for i in (b,c)):
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top