Sphener
Sphener

Reputation: 383

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.

Upvotes: 0

Views: 92

Answers (2)

vishes_shell
vishes_shell

Reputation: 23514

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

Upvotes: 3

Rory Daulton
Rory Daulton

Reputation: 22564

This is pythonic and would work:

if any(v in my_tuple for v in [foo, bar, eggs, spam, parrot, lumberjack]):

Upvotes: 10

Related Questions