Home / Python / Reference / Built-in functions

Python sum() function

Add up all the numbers in an iterable.

Syntax

sum(iterable, start=0)

Works on lists, tuples, ranges and generators of numbers. To join strings use "".join(...) instead.

Parameters

iterablenumbers to add
starta value to start from (default 0)

Return value

the total

Example

Code

print(sum([4, 8, 15, 16, 23, 42]))
print(sum(range(1, 101)))
prices = [4.5, 3.25, 12.0]
print(sum(prices))
print(sum(p * 2 for p in prices))     # with a generator expression
scores = [70, 85, 92]
print(sum(scores) / len(scores))      # the average

Output

108
5050
19.75
39.5
82.33333333333333

Related

Learn it step by step in the free lesson Loops, with exercises that check your answers.