04-24-2020, 03:19 AM
Python sum() List – A Simple Illustrated Guide
Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in function to sum over all elements in a Python list—or any other iterable for that matter. (Official Docs)
The syntax is:
Argument |
Description
|
Sum over all elements in the. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements.
Example: returns .
|
(Optional.) The default start value is 0. If you define another start value, the sum of all values in the will be added to this start value.
Example: returns .
Check out the Python Freelancer Webinar and KICKSTART your coding career!
Code: Let’s check out a practical example!
Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:
https://repl.it/@finxter/sumpythonlist?lite=true
Let’s explore some important details regarding the function in Python.
Errors
A number of errors can happen if you use the function in Python.
TypeError: Python will throw a TypeError if you try to sum over elements that are not numerical. Here’s an example:
If you run this code, you’ll get the following error message:
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:
Output:
You can get rid of all those errors by summing only over numerical elements in the list.
(For more information about the method, check out this blog article.)
Python Sum List Time Complexity
The time complexity of the 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? This is called string concatenation.
Solution: Use the method of Python strings to concatenate all strings in a list. The 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.
Python Sum List of Lists
Problem: How can you sum a list of lists such as 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.
The 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)?
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 function.
This is not the prettiest way but it’s readable and it works (and, you didn’t want to use the function, right?).
Python Sum List For Loop
Problem: How can you sum over all list elements using a for loop (without)?
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 function.
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 and you want to sum up the first and the second tuple values to obtain the “summed tuple” .
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:
Need a refresher of the 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. Sum up the slice with , , and .
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.
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 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 function to sum over the remaining values.
Code: The following code sums over all values that satisfy a certain condition (e.g.,).
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. How to sum over all values that are not the value ?
Example: Say, you’ve got the list and you want to sum over all values that are not .
Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from). You see, that’s a special case of the previous paragraph that checks for a general condition. Then, use the function to sum over the remaining values.
Code: The following code sums over all values that are not.
A similar thing can be done with the value 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 (=”not a number”). How to sum over all values that are not the value ?
Example: Say, you’ve got the list and you want to sum over all values that are not .
Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from). You see, that’s a special case of the previous paragraph that checks for a general condition. Then, use the function to sum over the remaining values.
Code: The following code sums over all values that are not.
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!
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!
Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in
Code:
sum()The syntax is
Code:
sum(iterable, start=0)Argument |
Description
Code:
iterableSum over all elements in the
Code:
iterableExample:
Code:
sum([1, 2, 3])Code:
1+2+3=6Code:
start(Optional.) The default start value is 0. If you define another start value, the sum of all values in the
Code:
iterableExample:
Code:
sum([1, 2, 3], 9)Code:
9+1+2+3=15Check out the Python Freelancer Webinar and KICKSTART your coding career!
Code: Let’s check out a practical example!
Code:
lst = [1, 2, 3, 4, 5, 6] print(sum(lst))
# 21 print(sum(lst, 10))
# 31Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:
https://repl.it/@finxter/sumpythonlist?lite=true
Let’s explore some important details regarding the
Code:
sum()Errors
A number of errors can happen if you use the
Code:
sum()TypeError: Python will throw a TypeError if you try to sum over elements that are not numerical. Here’s an example:
Code:
# Demonstrate possible execeptions
lst = ['Bob', 'Alice', 'Ann'] # WRONG:
s = sum(lst)If you run this code, you’ll get the following error message:
Code:
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:
Code:
# Demonstrate possible execeptions
lst = ['Bob', 'Alice', 'Ann'] # WRONG:
s = sum(lst, '')Output:
Code:
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
Code:
join()Python Sum List Time Complexity
The time complexity of the
Code:
sum()Python Sum List of Strings
Problem: How can you sum a list of strings such as
Code:
['python', 'is', 'great']Solution: Use the
Code:
join()Code:
sum()Code: The following example shows how to “sum” up (i.e., concatenate) all elements in a given list of strings.
Code:
# List of strings
lst = ['Bob', 'Alice', 'Ann'] print(''.join(lst))
# BobAliceAnn print(' '.join(lst))
# Bob Alice AnnProblem: How can you sum a list of lists such as
Code:
[[1, 2], [3, 4], [5, 6]]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.
Code:
# 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
Code:
extend()Python Sum List While Loop
Problem: How can you sum over all list elements using a while loop (without
Code:
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
Code:
sum()Code:
# 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)
# 15This is not the prettiest way but it’s readable and it works (and, you didn’t want to use the
Code:
sum()Python Sum List For Loop
Problem: How can you sum over all list elements using a for loop (without
Code:
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
Code:
sum()Code:
# 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)
# 15This 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
Code:
[(1, 1), (2, 0), (0, 3)]Code:
(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:
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
Code:
zip()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
Code:
[3, 4, 5, 6, 7, 8, 9, 10]Code:
lst[2:5:2]Code:
start=2Code:
stop=5Code:
step=2Solution: 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.
Code:
# 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
Code:
lst = [5, 8, 12, 2, 1, 3]Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain. Then, use the
Code:
sum()Code: The following code sums over all values that satisfy a certain condition (e.g.,
Code:
x>4Code:
# 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)
# 25Need 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
Code:
NoneCode:
NoneExample: Say, you’ve got the list
Code:
lst = [5, None, None, 8, 12, None, 2, 1, None, 3]Code:
NoneSolution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from
Code:
NoneCode:
sum()Code: The following code sums over all values that are not
Code:
NoneCode:
# 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)
# 31A similar thing can be done with the value
Code:
NanPython Sum List Ignore Nan
Problem: Given is a list of numerical values that may contain some values
Code:
nanCode:
nanExample: Say, you’ve got the list
Code:
lst = [1, 2, 3, float("nan"), float("nan"), 4]Code:
nanSolution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain (that are different from
Code:
nanCode:
sum()Code: The following code sums over all values that are not
Code:
nanCode:
# 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)]))
# 10Phew! 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!
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!

