The Python sum() function takes a list of numbers, and sums them up (totals/adds them all together). Here’s how to use it, with examples.
The concept of summing numbers is simple – take the numbers you wish to get the total of, and add them all together.
1 + 2 + 3 = 6
It’s basic arithmetic that you’ll use daily when writing computer software in any language.
Summing Numbers in Python
The sum() function in Python sums numbers. It’s a built-in function, which can be used anywhere in your code without having to import any dependencies.
The syntax for the sum() function is as follows:
- ITERABLE can be any Python iterable, containing numerical values
- Usually, this is a list of numbers
- START is an optional starting position within the sequence of supplied numbers to start summing from
- If not specified, it defaults to 0 (zero)
- This is an index value, so it starts counting at 0 — the first number in the list is at index 0, the second at index 1, and so on
Below, a list of numbers is summed:
numberList = [2, 6, 8, 3] numberSum = sum(numberList)
Only the last 3 numbers in the list can be summed by providing a start position:
numberList = [2, 6, 8, 3] numberSum = sum(numberList, 1)
Summing Floating Point Numbers with High Accuracy
If you are summing floating point values and require high accuracy in the results, use the math.fsum() function instead.
Otherwise, you are likely to run into floating point precision errors:
sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999
Above, an inaccurate result is returned by the sum() function – the answer should be 1, not 0.9999999999999999. math.fsum() will give the correct result:
import math math.fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
Trying to join/concatenate strings?
The syntax for joining strings is the same as adding values in Python – using the + operator.
Iterables can also be joined together using the itertools.chain() function.