Search code examples
pythonpython-2.7booleanboolean-expression

Python Boolean "In" and "Or" Statements Together


Say I want to check if either of two given elements are present in a given tuple, like:

if foo in my_tuple or bar in my_tuple:

Is there a more pythonic way to frame this expression? Specifically, if I want to check for several elements, the statements becomes annoyingly long. I've tried

if (foo or bar) in my_tuple:

But this chooses foo over bar and checks only for foo. Would appreciate any inputs on this.


Solution

  • If you get a lot of elements that you need to compare it's better to check intersection of set objects:

    if {foo, bar, other_vars} & set(my_tuple):
    

    BUT keep in mind that values should be hashable, if not, look at Rory Daulton answer