Tips and Tricks - Any Instead of Nested for-Loops

Suppose you have a list of strings and want to select all items, which match at least on of the patterns stored in a different list. Simply put, check against multiple string patterns. Instead of using two nested for-loops:

lst = ["hello", "fafaea", "hello world", "xxx world", "zzz"]
patterns = ["hello", "world"]
matches = []

for item in lst:
    for pattern in patterns:
        if pattern in item:
            matches.append(item)

print(matches)  # ['hello', 'hello world', 'xxx world']

... you can utilise Python's built-in any() function, which evaluates to True if at least one of the supplied items evaluates to True:

lst = ["hello", "fafaea", "hello world", "xxx world", "zzz"]
patterns = ["hello", "world"]
matches = [
    item
    for item in lst
    if any(pattern in item for pattern in patterns)
]

print(matches)  # ['hello', 'hello world', 'xxx world']

Groups: language reference