Python sum() function

Updated on Nov 10, 2019


The sum() function takes an iterable and returns the sum of items in it.

Syntax:

sum(iterable, [start]) -> number
PARAMETER DESCRIPTION
iterable (required) Iterable item like string, list, dictionary etc.
start (optional) An optional numeric value added to the final result. It defaults to 0.

The sum() function only works with numerical values, trying to use it with non-numeric type will result in an error.

Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> 
>>> sum([1, 2, 3, 4, 5]) # sum values in a list
15
>>> 
>>> sum((1, 2, 3, 4, 5)) # sum values in a tuple
15
>>> 
>>> sum({1, 2, 3, 4, 5}) # sum values in a set
15
>>> 
>>> sum({1: "one", 2: "two", 3: "three"}) # sum values in a 
6
>>>

Try it out:

print(sum([1, 2, 3, 4, 5])) # sum values in a list

print(sum((1, 2, 3, 4, 5))) # sum values in a tuple

print(sum({1, 2, 3, 4, 5})) # sum values in a set

print(sum({1: "one", 2: "two", 3: "three"})) # sum values in a 

In the last command, the sum() adds the keys in the dictionary, ignoring its values.

Here is another example, which specifies the start value to be added to the final result.

1
2
3
4
>>> 
>>> sum([10, 20, 30], 100)
160
>>>

Try it out:

print(sum([10, 20, 30], 100))

Other Tutorials (Sponsors)