Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python any() function

Reference for Python any(): test whether at least one item of an iterable is truthy, why an empty iterable gives False, short-circuiting and generator use.

The built-in any() function takes an iterable and returns True if at least one item is truthy. If every item is falsy, or the iterable is empty, it returns False. It stops reading as soon as it finds a truthy item.

Combine it with a generator expression to ask "does any element match?": is any file a PDF, is any score a failure, does the text contain any banned word.

Python
any([0, "", 5])     # True
any([0, "", None])  # False

Try it

Python Does anything match?

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 and any vs in

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
any(iterable)
Name Description
iterable Any iterable: list, tuple, set, string, dict (checks the keys), generator, ...

Return value: True if some item is truthy; False if all items are falsy or the iterable is empty. Always a bool.

Raises: TypeError if the argument is not iterable.

Usage notes

  • Empty means False. any([]) is False, the mirror of all([]) being True.
  • Truthiness, not equality. The items themselves are tested, so any(["", 0]) is False and any(["0"]) is True. To test a condition, produce booleans with a generator expression.
  • Short-circuits. The first truthy item ends the search, so the rest of a generator is never evaluated. That also makes any() safe on very long or infinite iterators.
  • Use in for plain membership. x in items is clearer and faster than any(item == x for item in items).
  • Dictionaries are iterated by key; use .values() for values.
  • Prefix and suffix checks. str.startswith() and str.endswith() accept a tuple, so name.endswith((".png", ".jpg")) replaces any(name.endswith(e) for e in exts).
  • Opposite. not any(...) means "none match", and is equal to all(not ...).