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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Interestingly enough, it applies to my use case. I should have used sets from the beginning. Thanks!
4

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.