0

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.

Sphener
  • 183
  • 1
  • 1
  • 7
  • 1
    Possible duplicate of [Can Python test the membership of multiple values in a list?](https://stackoverflow.com/questions/6159313/can-python-test-the-membership-of-multiple-values-in-a-list) – Ilja Everilä Jun 08 '17 at 10:38

2 Answers2

10

This is pythonic and would work:

if any(v in my_tuple for v in [foo, bar, eggs, spam, parrot, lumberjack]):
Rory Daulton
  • 20,571
  • 5
  • 39
  • 47
3

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

vishes_shell
  • 20,161
  • 6
  • 65
  • 77