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.
any([0, "", 5]) # True any([0, "", None]) # False
Try it
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.
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
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([])isFalse, the mirror ofall([])beingTrue. - Truthiness, not equality. The items themselves are tested, so
any(["", 0])isFalseandany(["0"])isTrue. 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
infor plain membership.x in itemsis clearer and faster thanany(item == x for item in items). - Dictionaries are iterated by key; use
.values()for values. - Prefix and suffix checks.
str.startswith()andstr.endswith()accept a tuple, soname.endswith((".png", ".jpg"))replacesany(name.endswith(e) for e in exts). - Opposite.
not any(...)means "none match", and is equal toall(not ...).
Related
all(),bool(),filter(),str.endswith()- Lessons: Booleans, Membership and identity, Comprehensions