Python sum() – A Simple Illustrated Guide

Summing up numbers is one of those repetitive tasks you need to do over and over again in your practical code projects.

To help you accomplish this task in a concise, readable, and efficient way, Python’s creators have added the built-in sum() function. It sums over all elements in a Python list—or any other iterable for that matter. (Official Docs)

Python sum() - Visual Example

Python sum() Syntax

The syntax is sum(iterable, start=0):

iterableSum over all elements in the iterable. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements.
Example: sum([1, 2, 3]) returns 1+2+3=6.
start(Optional.) The sum of all values in the iterable will be added to this start value. The default start value is 0.
Example: sum([1, 2, 3], 9) returns 9+1+2+3=15.

Python sum() Video

Check out the Python Freelancer Webinar and KICKSTART your coding career!

Python sum() Example

Code: Let’s check out a practical example!

lst = [1, 2, 3, 4, 5, 6]

# 21

print(sum(lst, 10))
# 31

Let’s explore some important details regarding the sum() function in Python.

Python sum() Time Complexity

The time complexity of the sum() function is linear in the number of elements in the iterable (list, tuple, set, etc.). The reason is that you need to go over all elements in the iterable and add them to a sum variable. Thus, you need to “touch” every iterable element once.

Python sum() Dictionary Values

Problem: How to sum all values in a dictionary?

Solution: Use sum(dict.values()) to sum over all values in a dictionary.

customers = {'Alice': 10000,
             'Bob': 9900,
             'Carl': 21100}

# total sales:
total = sum(customers.values())

# print result:
print('Sales: ', total)
# Sales:  41000

Python sum() List of Strings

Problem: How can you sum a list of strings such as ['python', 'is', 'great']? This is called string concatenation.

Solution: Use the join() method of Python strings to concatenate all strings in a list. The sum() function works only on numerical input data.

Code: The following example shows how to “sum” up (i.e., concatenate) all elements in a given list of strings.

# List of strings
lst = ['Bob', 'Alice', 'Ann']

# BobAliceAnn

print(' '.join(lst))
# Bob Alice Ann

Python sum() List of Lists

Problem: How can you sum a list of lists such as [[1, 2], [3, 4], [5, 6]] in Python?

Solution: Use a simple for loop with a helper variable to concatenate all lists.

Code: The following code concatenates all lists into a single list.

# List of lists
lst = [[1, 2], [3, 4], [5, 6]]

s = []
for x in lst:
# [1, 2, 3, 4, 5, 6]

The extend() method is little-known in Python—but it’s very effective to add a number of elements to a Python list at once. Check out my detailed tutorial on this Finxter blog.

Python sum() List of Tuples Element Wise

Problem: How to sum up a list of tuples, element-wise?

Example: Say, you’ve got list [(1, 1), (2, 0), (0, 3)] and you want to sum up the first and the second tuple values to obtain the “summed tuple” (1+2+0, 1+0+3)=(3, 4).

Solution: Unpack the tuples into the zip function to combine the first and second tuple values. Then, sum up those values separately. Here’s the code:

# list of tuples
lst = [(1, 1), (2, 0), (0, 3)]

# aggregate first and second tuple values
zipped = list(zip(*lst))
# result: [(1, 2, 0), (1, 0, 3)]

# calculate sum of first and second tuple values
res = (sum(zipped[0]), sum(zipped[1]))

# print result to the shell
# result: (3, 4)

Need a refresher of the zip() function and unpacking? Check out these articles on the Finxter blog:

Python sum() List Slice

Problem: Given a list. Sum up a slice of the original list between the start and the step indices (and assuming the given step size as well).

Example: Given is list [3, 4, 5, 6, 7, 8, 9, 10]. Sum up the slice lst[2:5:2] with start=2, stop=5, and step=2.

Solution: Use slicing to access the list. Then, apply the sum() function on the result.

Code: The following code computes the sum of a given slice.

# create the list
lst = [3, 4, 5, 6, 7, 8, 9, 10]

# create the slice
slc = lst[2:5:2]

# calculate the sum
s = sum(slc)

# print the result
# 12 (=5+7)

Let’s examine an interesting problem: to sum up conditionally!

Python sum() List Condition

Problem: Given is a list. How to sum over all values that meet a certain condition?

Example: Say, you’ve got the list lst = [5, 8, 12, 2, 1, 3] and you want to sum over all values that are larger than 4.

Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain. Then, use the sum() function to sum over the remaining values.

Code: The following code sums over all values that satisfy a certain condition (e.g., x>4).

# create the list
lst = [5, 8, 12, 2, 1, 3]

# filter the list
filtered = [x for x in lst if x>4]
# remaining list: [5, 8, 12]

# sum over the filtered list
s = sum(filtered)

# print everything
# 25

Need a refresher on list comprehension? Check out my in-depth tutorial on the Finxter blog.

Python sum() Errors

A number of errors can happen if you use the sum() function in Python.

TypeError: Python throws a TypeError if you try to sum over non-numerical elements.

For example:

# Demonstrate possible execeptions
lst = ['Bob', 'Alice', 'Ann']

s = sum(lst)

If you run this code, you’ll get the following error message:

Traceback (most recent call last):
  File "", line 3, in <module>
    s = sum(lst)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Python attempts to concatenate strings using the default start value of 0 (an integer). But as you cannot concatenate a string with an integer, this fails.

If you try to “hack” Python by using an empty string as start value, you’ll get the following exception:

# Demonstrate possible execeptions
lst = ['Bob', 'Alice', 'Ann']

s = sum(lst, '')


Traceback (most recent call last):
  File "", line 5, in <module>
    s = sum(lst, '')
TypeError: sum() can't sum strings [use ''.join(seq) instead]

You can get rid of all those errors by summing only over numerical elements in the list.

For more information about the join() method, check out this blog article.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!