← Python lessons

Python sum(), max() and min(): Built-in Accumulators

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Python's sum(), len(), max() and min() are built-in accumulators: each runs a common loop for you and returns the result.

Read The Accumulator Pattern first. You should know how a loop builds a total or a count.

This lesson shows when one call can replace a loop, and when you still need the loop. Every block runs on its own with fixed data, and the text under it says what it prints.

Add up a list with sum()

sum() adds every number in a list. It does the same work as a total that starts at 0.

rolls = [3, 5, 2]
print(sum(rolls))
print(len(rolls))
print(sum(rolls) / len(rolls))

This prints 10, 3 and 3.3333333333333335. len() counts every item, so sum() divided by len() gives the average.

Find the biggest and smallest

max() returns the largest item and min() the smallest.

rolls = [3, 5, 2, 6]
print(max(rolls))
print(min(rolls))

This prints 6 and 2. Both also work on strings: max(["ant", "bee"]) is "bee", the last in alphabetical order.

Know the edge cases

sum([]) is 0, but max() and min() have no answer for an empty list. They raise ValueError.

print(sum([]))
try:
    print(max([]))
except ValueError:
    print("max() needs at least one item")
print(max([], default=0))

This prints 0, the error message, then 0. The default= value is what max() returns when the list is empty. Pass it whenever an empty list is possible.

Choose a loop or a built-in

Use a built-in when it is the whole task. Use a loop when each item needs a decision first, such as adding only the big rolls.

rolls = [3, 5, 2, 6]
big_total = 0
for roll in rolls:
    if roll >= 4:
        big_total = big_total + roll
print(big_total)
print(sum(roll for roll in rolls if roll >= 4))

Both lines print 11. The second passes sum() a generator expression: it reads as "each roll in rolls, kept only if roll >= 4". Use it once you can write the loop version.

Note: This lesson leaves out max() with key=, which picks the best item by a rule you choose. See Tracking the Best Candidate for the loop version.

See also: Choosing the starting value.

Your turn

Print the total, the average, the highest and the lowest of scores, one per line. Use built-ins, not a loop.

scores = [8, 4, 9, 7]
# add four prints: sum, average, max, min

Expected output

28
7.0
9
4