3

The question is about a quicker, ie. more pythonic, way to test if any of the elements in an iterable exists inside another iterable.

What I am trying to do is something like:

if "foo" in terms or "bar" in terms or "baz" in terms: pass

But apparently this way repeats the 'in terms' clause and bloats the code, especially when we are dealing with many more elements. So I wondered whether is a better way to do this in python.

Thanasis Papoutsidakis
  • 1,661
  • 1
  • 12
  • 13
  • possible duplicate of [Python Check if one of the following items is in a list](http://stackoverflow.com/questions/740287/python-check-if-one-of-the-following-items-is-in-a-list) – Eric Mar 20 '14 at 12:34

3 Answers3

5

You could also consider in your special case if it is possible to use sets instead of iterables. If both (foobarbaz and terms) are sets, then you can just write

if foobarbaz & terms:
    pass

This isn't particularly faster than your way, but it is smaller code by far and thus probably better for reading.

And of course, not all iterables can be converted to sets, so it depends on your usecase.

Alfe
  • 56,346
  • 20
  • 107
  • 159
4

Figured out a way, posting here for easy reference. Try this:

if any(term in terms for term in ("foo", "bar", "baz")): pass

Thanasis Papoutsidakis
  • 1,661
  • 1
  • 12
  • 13
3

Faster than Alfe's answer, since it only tests for, rather than calculates the, intersection

if not set(terms).isdisjoint({'foo', 'bar', 'baz'}):
    pass
Eric
  • 95,302
  • 53
  • 242
  • 374