A list contains the numbers 10, 20 and 5: its sum is 35. We can a for
-loop to iterate and add up the element values. Or we can use a simpler built-in method.
The sum()
built-in receives 2 arguments. The first is an iterable
collection like list—these elements are summed. The second argument is added to the sum.
Here we introduce a list with 3 integers in it. We sum those integers with the sum()
built-in method. And then we use sum with 2 arguments.
iterable
like a list we want to sum. The list must have summable elements like integers, not sub lists.iterable
's elements. We can use this argument to sum previous sums.values = [1, 1, 2] # The sum of the 3 values is this number. result = sum(values) print(result) # Use sum with 2 arguments. # ... The second argument is added to the element sum. result = sum(values, 1000) print(result)4 1004
We cannot sum nested iterables. Instead sum()
only counts up top-level elements in our list. A nested list leads to a TypeError
.
# This list has a nested list element. # ... It cannot be summed with sum. values = [10, [20, 30]] # This will cause a TypeError. result = sum(values) print(result)Traceback (most recent call last): File "C:\programs\file.py", line 9, in <module> result = sum(values) TypeError: unsupported operand type(s) for +: 'int' and 'list'
The sum()
built-in will work with float
numbers like 1.5. But it may return a less-accurate result than the math.fsum
specialty method.
Why use sum? Why not just loop over elements and add them up? In some programs, sum()
leads to simpler, more maintainable code, and this causes fewer bugs.