Learn all about the sum() function in Python: from the syntax to use it with various iterables—with helpful code examples.

When working with Python iterables, such as a list of numbers, a common operation is to find the sum of all elements in the list. We’ll run into such operations when working with other iterables, such as tuples and sets, too.

This can be done in a few different ways, but the recommended Pythonic way is using the built-in sum() function.

Here, we’ll start by looking at the other approaches, such as looping and defining a function. We’ll then proceed to learn the syntax of Python’s sum() function and code examples to understand it better.

Summing Values in a Python Iterable

Summing-Values-in-a-Python-Iterable

📋 You can code along in a Python REPL. Or you can use Geekflare’s Online Python editor.

Consider the following list of numbers:

>>> nums = [2,8,5,3,11,7,9]

Our goal is to find the sum of all numbers in the list. We’ll get to the Python sum() function soon, but we’ll start with some of the other approaches we can take. These include:

  • Using a simple for loop
  • Using the reduce() function from the functools module
  • Defining a custom function

Using Loops

To find the sum of all elements in a list, we can use a for loop like so:

  • Initialize total variable to zero.
  • Loop through the nums list and access each number.
  • Add the number to the total.
>>> nums = [2,8,5,3,11,7,9]
>>> total = 0
>>> for num in nums:
...     total += num
...
>>> total
45

Using the Reduce Function

Another approach to summing iterables is using the reduce() function. The reduce function, built into Python’s functools module, takes in a function and an iterable. And reduces the iterable by successively applying the function on the elements of the iterable.

Here, we use a lambda function to define the addition of two numbers and pass in nums list as the iterable.

>>> nums = [2,8,5,3,11,7,9]
>>> from functools import reduce
>>> total = reduce(lambda n1, n2: n1 + n2, nums)
>>> total
45

The reduce() function works by successively adding two numbers—from left to right—until it reduces to a single sum value:

Using-the-Reduce-Function

Using a Custom Function

We can also define a custom function to do this. Here, we define a function sum_list that:

  • Takes in a list of numbers as the argument and 
  • Returns the sum of elements in a list.

The body of the function uses the looping construct we looked at earlier. But defining a function gives us reusability.

>>> def sum_list(some_list):
...     total = 0
...     for num in some_list:
...        total += num
...     return total
...

Calling the sum_list() function with nums as the arguments returns the sum of 45:

>>> nums = [2,8,5,3,11,7,9]
>>> total = sum_list(nums)
>>> total
45

 Next, let’s learn about the built-in sum() function. It’s not only concise but also robust in that it works well with several iterables and data types.

Syntax of the Python Sum Function

The syntax to use the sum() function is as follows:

sum(iterable, start)

Here,

  • iterable is a required argument. It can be any iterable for which the summing operation is valid such as a list or tuples of numbers. Calling the sum() function with Python strings raises a TypeError exception (more on this later).
  • start is an optional argument. It is often a numeric value that is added to the computed sum. This can be helpful when you need to add a constant value to the result.

Now that we’ve learned the syntax of the Python sum() function, let’s use it to sum iterables.

Summing Iterables with Sum Function

Summing-Iterables-with-Pythons-Sum-Function

#1. List

Let’s find the sum of numbers in the nums list using the sum() function:

>>> nums = [2,8,5,3,11,7,9]
>>> sum_1 = sum(nums)
>>> sum_1
45

Using the Optional Start Value

To add a constant value to the sum, we can use the sum() function with the optional start value. Here, we pass in a start value of 100 as a positional argument:

>>> sum_start = sum(nums,100)
>>> sum_start
145

The start value can also be specified as a keyword argument:

>>> sum_start = sum(nums,start=10)
>>> sum_start
55

#2. Tuple

The sum() function also works with tuples. We create a tuple nums_tuple by casting the nums list to a tuple:

>>> nums_tuple = tuple(nums)
>>> nums_tuple
(2, 8, 5, 3, 11, 7, 9)
>>> sum_2 = sum(nums_tuple)
>>> sum_2
45

#3. Set

We can also use the sum() function with a set of numbers:

>>> nums_set = set(nums)
>>> nums_set
{2, 3, 5, 7, 8, 9, 11}

Here, we cast the nums list to a Python set and compute the sum of elements in nums_set.

>>> sum_3 = sum(nums_set)
>>> sum_3
45

#4. Dictionary

Consider the following student_dict with numeric keys. Notice what happens when you call the sum() function with this dictionary as the argument.

>>> students_dict = {1:106,2:112,3:127}
>>> sum_4 = sum(students_dict)
>>> sum_4
6

The sum() function, by default, returns the sum of the keys.

Summing the Keys

We know that the default behavior is to sum the keys of the dictionary.

However, you can make this more explicit by using the dictionary method keys() to access the keys. And then pass in the list of keys to the sum() function:

>>> sum_keys = sum(students_dict.keys())
>>> sum_keys
6

Summing the Values

If you’d like to sum the values of the dictionary instead, access the values by calling the values() method on the dictionary object:

>>> sum_vals = sum(students_dict.values())
>>> sum_vals
345

Using Python’s Sum Function with Other Numeric Data Types

Using-Pythons-Sum-Function-with-Other-Numeric-Data-Types

So far, we have seen how to use the sum() function with iterables of integers. Now let’s look at a couple of examples with other numeric data types.

Complex Numbers

The sum() function can also be used to sum complex numbers. In this example, nums_c is a list of complex numbers:

>>> nums_c = [3 + 4j, 1 + 2j]
>>> sum_c = sum(nums_c)
>>> sum_c
(4+6j)

Floating Point Numbers

Here, we use the sum() function to sum the list of floating point numbers nums_f:

>>> nums_f = [1.8,2.5,3.6,7.2]
>>> sum_f = sum(nums_f)
>>> sum_f
15.100000000000001

📑 For improved precision in the result of adding floating point numbers, you can use the fsum() function from the math module to sum iterables with floating point values.

Flattening with the Sum Function

Now let’s see how the sum() function can be used to flatten and concatenate iterables.

Flatten a List

Suppose we have a nested list:

>>> lists = [[2,4,6],[3,5,7]]

When we call the sum() function by passing in this nested list as the argument along with an empty list as the start value:

>>> sum(lists,[])
[2, 4, 6, 3, 5, 7]

We see that the nested list has now then flattened into a single list of numbers.

Equivalently, when we think of the list to be of the form l3 = [l1,l2], the sum() function concatenates the two lists l1 and l2 nested within the list l3.

📝As a quick exercise, try using the sum() function on other nested iterables.

Common Pitfall: Don’t Use Python’s sum() Function with Strings

Because we have seen that the sum() function can be used to flatten and concatenate lists (and other iterables like tuples); it’s tempting to think that we can use it to concatenate strings as well.

But if you try to do so, you’ll run into a TypeError:

>>> sum(['a','b','c'],'')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

So the sum() function cannot be used to sum (or concatenate) strings.

However, as seen in the error message above, you can use the join() method to concatenate a list of strings into a single string.

>>> ''.join(['a','b','c'])
'abc'

Conclusion

In this tutorial, we learned how to use the built-in sum() function to find the sum of all elements in an iterable. The general syntax to use the sum() function is: sum(iterable, start), where iterable is a required argument and start is an optional argument.

We then coded several examples to understand the use of the sum() function with iterables like lists, tuples, sets, and dictionaries. Later, we looked at how the sum() function can be used for flattening and concatenating iterables—with the exception of Python strings.

I hope you found this tutorial helpful. Next, you may want to check out this tutorial on Python’s map function.