How to use the Python sum() Function

The Python sum() function is used to get the sum of all elements in an iterable.

 

sum() Syntax

sum() takes two arguments, the iterable and the start value.

 

sum(iterable, [start])

 

  • iterable – any iterable data such as a string, dictionary or list.
  • start – an optional argument to specify where to start counting from. If not supplied sum() will start at 0.

 

Get Sum of List Elements

The example below demonstrates how to get the sum of all elements in a Python list.

 

items = [1, 5, 10]

result = sum(items)

print(result)
16

 

Get Sum of Iterable Plus N

Here is another example demonstrating how to generate a sum with an additional value to add to the final result:

 

items = [1, 5, 10]

result = sum(items, 2)

print(result)
18