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 ag values are pre-defined, then a tuple would indeed be preferred. See: Are tuples more efficient than lists in Python?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)