0
0
PythonHow-ToBeginner · 3 min read

How to Use any() and all() in Python: Simple Guide

In Python, any() returns True if at least one element in an iterable is true, while all() returns True only if every element is true. Use them to quickly check conditions across lists, tuples, or other collections.
📐

Syntax

any(iterable): Returns True if any element in the iterable is true. Returns False if all are false or iterable is empty.

all(iterable): Returns True if all elements in the iterable are true. Returns False if any element is false or iterable is empty.

python
any(iterable)
all(iterable)
💻

Example

This example shows how any() and all() work with a list of boolean values and numbers.

python
values = [0, 1, 2, 3]
print(any(values))  # True because 1, 2, 3 are true
print(all(values))  # False because 0 is false

bools = [True, True, False]
print(any(bools))   # True because at least one True
print(all(bools))   # False because not all are True
Output
True False True False
⚠️

Common Pitfalls

One common mistake is using any() or all() on empty iterables. any([]) returns False and all([]) returns True, which can be surprising.

Also, remember that these functions check the truthiness of elements, so values like 0, '' (empty string), and None count as false.

python
empty_list = []
print(any(empty_list))  # False
print(all(empty_list))  # True

mixed = [0, '', None]
print(any(mixed))  # False
print(all(mixed))  # False
Output
False True False False
📊

Quick Reference

FunctionReturns True WhenReturns False When
any(iterable)At least one element is trueAll elements are false or iterable is empty
all(iterable)All elements are trueAt least one element is false

Key Takeaways

Use any() to check if any element in a collection is true.
Use all() to check if every element in a collection is true.
Empty iterables return False for any() and True for all().
These functions test the truthiness of elements, so zero, empty strings, and None count as false.
They work with any iterable like lists, tuples, sets, or generators.