Built-in sum function in Python

Last updated: Mon. Sep. 14, 2026

Python's sum() function is used to find the total of numbers in an iterable (i.e. list, tuple, set or dictionary). A simple example is:

print(sum([8, 5, 7]))

This will return 20 because 0 + 8 + 5 + 7 = 20. The 0 here is the default value of the start argument. The sum function has a start argument which when modified, begins adding the items in the iterable (from left to right) to the given start value and returns the total. For example if you run the code:

print(sum([4, 6, 9], start=6))

you will get 25 because 6 + 6 + 6 + 9 = 25. The iterable’s items are normally numbers, and the start value cannot be a string.

The sum() function can also be used to flatten a list. Consider the following list:

matrix = [[1, 6], [5, 3], [2,9]]

One way to flatten this is to use nested for-loops:

flattened = []

for inner in matrix:

       for item in inner:

              flattened.append(item)

A simpler way would be list comprehension:

flattened = [item for inner in matrix for item in inner]

A more elegant solution would be to use the sum() function and passing an empty list:

print(sum(matrix, []))

The result would be the same for each of those methods:

[1, 6, 5, 3, 2, 9]

« Home