Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in sum()
function to sum over all elements in a Python list—or any other iterable for that matter. (Official Docs)
The syntax is sum(iterable, start=0)
:
Argument | Description |
---|---|
iterable | Sum 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 default start value is 0. If you define another start value, the sum of all values in the iterable will be added to this start value. Example: sum([1, 2, 3], 9) returns 9+1+2+3=15 . |
Check out the Python Freelancer Webinar and KICKSTART your coding career!
Code: Let’s check out a practical example!
lst = [1, 2, 3, 4, 5, 6] print(sum(lst)) # 21 print(sum(lst, 10)) # 31
Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:
Let’s explore some important details regarding the sum()
function in Python.
Errors
A number of errors can happen if you use the sum()
function in Python.
TypeError: Python will throw a TypeError if you try to sum over elements that are not numerical. Here’s an example:
# Demonstrate possible execeptions lst = ['Bob', 'Alice', 'Ann'] # WRONG: s = sum(lst)
If you run this code, you’ll get the following error message:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 3, in <module> s = sum(lst) TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python tries to perform string concatenation using the default start value of 0 (an integer). Of course, this fails. The solution is simple: sum only over numerical values in the list.
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'] # WRONG: s = sum(lst, '')
Output:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", 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.)
Python Sum List 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 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'] print(''.join(lst)) # 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: s.extend(x) print(s) # [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 While Loop
Problem: How can you sum over all list elements using a while loop (without sum()
)?
Solution: Create an aggregation variable and iteratively add another element from the list.
Code: The following code shows how to sum up all numerical values in a Python list without using the sum()
function.
# list of integers lst = [1, 2, 3, 4, 5] # aggregation variable s = 0 # index variable i = 0 # sum everything up while i<len(lst): s += lst[i] i += 1 # print the result print(s) # 15
This is not the prettiest way but it’s readable and it works (and, you didn’t want to use the sum()
function, right?).
Python Sum List For Loop
Problem: How can you sum over all list elements using a for loop (without sum()
)?
Solution: Create an aggregation variable and iteratively add another element from the list.
Code: The following code shows how to sum up all numerical values in a Python list without using the sum()
function.
# list of integers lst = [1, 2, 3, 4, 5] # aggregation variable s = 0 # sum everything up for x in lst: s += x # print the result print(s) # 15
This is a bit more readable than the previous version with the while loop because you don’t have to keep track about the current index.
Python Sum List with List Comprehension
List comprehension is a powerful Python features that allows you to create a new list based on an existing iterable. Can you sum up all values in a list using only list comprehension?
The answer is no. Why? Because list comprehension exists to create a new list. Summing up values is not about creating a new list. You want to get rid of the list and aggregate all values in the list into a single numerical “sum”.
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 print(res) # 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 print(s) # 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 print(s) # 25
Need a refresher on list comprehension? Check out my in-depth tutorial on the Finxter blog.
Python Sum List Ignore None
Problem: Given is a list of numerical values that may contain some values None
. How to sum over all values that are not the value None
?
Example: Say, you’ve got the list lst = [5, None, None, 8, 12, None, 2, 1, None, 3]
and you want to sum over all values that are not None
.
Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from None
). You see, that’s a special case of the previous paragraph that checks for a general condition. Then, use the sum()
function to sum over the remaining values.
Code: The following code sums over all values that are not None
.
# create the list lst = [5, None, None, 8, 12, None, 2, 1, None, 3] # filter the list filtered = [x for x in lst if x!=None] # remaining list: [5, 8, 12, 2, 1, 3] # sum over the filtered list s = sum(filtered) # print everything print(s) # 31
A similar thing can be done with the value Nan
that can disturb your result if you aren’t careful.
Python Sum List Ignore Nan
Problem: Given is a list of numerical values that may contain some values nan
(=”not a number”). How to sum over all values that are not the value nan
?
Example: Say, you’ve got the list lst = [1, 2, 3, float("nan"), float("nan"), 4]
and you want to sum over all values that are not nan
.
Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from nan
). You see, that’s a special case of the previous paragraph that checks for a general condition. Then, use the sum()
function to sum over the remaining values.
Code: The following code sums over all values that are not nan
.
# for checking isnan(x) import math # create the list lst = [1, 2, 3, float("nan"), float("nan"), 4] # forget to ignore 'nan' print(sum(lst)) # nan # ignore 'nan' print(sum([x for x in lst if not math.isnan(x)])) # 10
Phew! Quite some stuff. Thanks for reading through this whole article! I hope you’ve learned something out of this tutorial and remain with the following recommendation:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.