Python all(), any(), min(), max(), and sum()
Learn Python built-in aggregation functions for truth checks, extremes, and totals: all(), any(), min(), max(), and sum().
Basic
Python has several built-in functions that answer a single question about an iterable or combine its values into one result. In this lesson, you will use
all(),
any(),
min(),
max(), and
sum().
These functions are useful when a loop would otherwise exist only to compute one final answer. They do not replace iteration itself; they provide common, focused operations over iterables.
Check whether every item is true
The
all() function returns
True when every item in its iterable is truthy. It also returns
True for an empty iterable.
Output
Ready to run.
Check whether at least one item is true
The
any() function returns
True when at least one item in its iterable is truthy. It returns
False for an empty iterable.
Output
Ready to run.
all() and any() stop when the answer is known
Both functions consume their iterable only as far as needed. Once
all() finds a false item, it can return
False. Once
any() finds a true item, it can return
True.
Output
Ready to run.
Find the smallest and largest item
With one positional argument,
min() and
max() expect an iterable and return its smallest or largest item. With two or more positional arguments, they compare those arguments directly.
Output
Ready to run.
Use key and default with min() and max()
Like
sorted(),
min() and
max() can receive a
key function that determines what is compared while the original items are returned. They also support
default when the single iterable is empty.
Output
Ready to run.
Ties return the first matching item
If several items are tied for the minimum or maximum, the built-in returns the first one encountered. This is useful when the items carry information beyond the value used for comparison.
Output
Ready to run.
Add values with sum()
The
sum() function adds the items of an iterable from left to right and returns the total. Its optional
start value is included in that total and defaults to zero.
Output
Ready to run.
Choose the smallest operation that answers the question
Use
all() for “does every item pass?”,
any() for “does at least one pass?”,
min() or
max() when one extreme item is needed, and
sum() when the items should be totaled.
Output
Ready to run.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.