Does Python have a cleaner way to express "if x contains a|b|c|d..."? [duplicate]
The Pythonic approach would be to use any()
:
if any(s in x for s in (a,b,c,d,e,f,g)):
From the linked documentation:
any
(iterable)Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
def any(iterable): for element in iterable: if element: return True return False
Also, notice that I've used a tuple instead of a list here. If your a
-g
values are pre-defined, then a tuple would indeed be preferred. See: Are tuples more efficient than lists in Python?
if any(q in x for q in [a,b,c,d,e,f,g]):
I think that's about as short & Pythonic as you can get it.
A bit late to the party, but
not frozenset(x).isdisjoint(frozenset(y))
would work, and may be faster (algorithmically, but maybe not for smaller test cases).