Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python all() function

Reference for Python all(): test whether every item of an iterable is truthy, why an empty iterable gives True, short-circuiting and use with generators.

The built-in all() function takes an iterable and returns True if every item is truthy, otherwise False. It stops as soon as it meets a falsy item, so it does not always read the whole iterable.

It is most often paired with a generator expression to check a rule against every element: all scores are positive, all fields are filled in, all words are lower case.

Python
all([1, "a", True])    # True
all([1, 0, 3])         # False

Try it

Python Checking every item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Short-circuiting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
all(iterable)
Name Description
iterable Any iterable: list, tuple, set, string, dict (checks the keys), generator, ...

Return value: True if all items are truthy or the iterable is empty; False otherwise. The result is always a real bool, not one of the items.

Raises: TypeError if the argument is not iterable.

Usage notes

  • Empty means True. all([]) is True, because no item breaks the rule. When "at least one item must exist" matters, check len() or the truthiness of the collection too: bool(items) and all(...).
  • Truthiness, not equality. 0, 0.0, "", None, [], {} and False count as false; all(["0"]) is True because the string "0" is not empty.
  • Short-circuits. all() stops at the first falsy item. With a generator expression the remaining items are never produced, which saves time and lets you test infinite iterators.
  • Dictionaries are iterated by key. Use .values() to test values.
  • Generator vs list. all(x > 0 for x in data) is lazy; all([x > 0 for x in data]) builds the whole list first. Prefer the generator form.
  • Exhausts iterators. Passing an iterator consumes it up to the stopping point; the part already read is gone.
  • Opposite. all(not x for x in items) means none is true, which is not any(items).