← Python lessons

Python any() and all(): Search a List in One Line

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

any() returns True if at least one value is true. all() returns True if every value is true. Each one replaces a whole search loop with one call.

Read Stopping a Search with return first. The examples also use generator expressions, explained in Generator expressions.

any() on a list of Booleans

The simplest form takes a list of True and False values.

print(any([False, True, False]))
print(all([False, True, False]))
print(all([True, True]))

It prints True, False and True.

Replace a search loop with any()

Put the test from the if inside any(), followed by the for part of the loop.

def contains_negative(numbers):
    return any(number < 0 for number in numbers)

print(contains_negative([4, -2, 7]))
print(contains_negative([4, 2, 7]))

number < 0 for number in numbers is a generator expression. It works out one True or False per number, only when any() asks for the next one. So any() stops at -2 and never tests 7.

The result matches the loop in the fundamentals lesson: True as soon as one number is negative, otherwise False.

Replace an "every value" check with all()

all() is the flipped search. It stops with False at the first value that fails.

def all_even(numbers):
    return all(number % 2 == 0 for number in numbers)

print(all_even([2, 4, 8]))
print(all_even([2, 3, 8]))

It prints True, then False. all_even([2, 3, 8]) stops at 3.

Watch out: empty lists

With nothing to check, any() returns False and all() returns True. No value failed, so "all of them pass" is true.

print(any([]))
print(all([]))

This matches the loop version: an empty list skips the loop and reaches the return after it.

When to keep the loop

Both functions stop early, like return in a loop. Use them when you only need True or False. Keep a loop when you need the matching item, its position, or to print or count along the way.

Note: any() and all() test truthiness, so any([0, ""]) is False. Passing a list in square brackets builds the whole list first; the bracket-free form stops building values early too.

See also: Truthy and falsy values, Returning the found value.

Your turn

Write all_short(words) with all() and any_starts_with(words, letter) with any(). A short word has 4 letters or fewer. word.startswith(letter) is True when word begins with letter. Run it to see False, True, False, True.

def all_short(words):
    # return all(...) over the words
    pass

def any_starts_with(words, letter):
    # return any(...) over the words
    pass

words = ["kiwi", "plum", "banana"]
print(all_short(words))
print(any_starts_with(words, "p"))
print(any_starts_with(words, "z"))
print(all_short([]))

Expected output

False
True
False
True