Problem: Given a list of lists representing a data matrix with n rows and m columns. How to sum over the rows of this matrix? In this article, you’re going to learn different ways to accomplish this in Python.
Let’s ensure that you’re on the same page. Here’s a graphical representation of the list of lists and what you want to achieve:
Example: Given the following code.
# Your list of lists data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # ... Algorithm here ... print(res) # OUTPUT: [6, 15, 24]
Background: To learn more about list of lists, check out our reference article on the Finxter blog.
Next, you’ll learn three different methods to sum over the rows. Let’s get a quick overview of all three methods—click “Run” to execute the code and see what happens!
Method 1: Sum in Python (No Library)
A simple one-liner with list comprehension does the job in Python.
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Method 1: Pure Python res = [sum(x) for x in data] print(res) # [6, 15, 24]
Do you love Python one-liners? I do for sure—I’ve even written a whole book about it with San Francisco Publisher NoStarch. Click to check out the book in a new tab:
You can visualize the code execution and memory objects of this code in the following tool (just click “Next” to see how one step of the code unfolds).
Method 2: Sum with NumPy Library
You create a NumPy array out of the data and pass it to the np.sum() function.
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Method 2: NumPy import numpy as np a = np.array(data) res = np.sum(a, axis=1) print(res) # [ 6 15 24]
axis argument of the sum function defines along which axis you want to calculate the sum value. If you want to sum over columns, use
axis=0. If you want to sum over rows, use
axis=1. If you want to sum over all values, skip this argument.
Method 3: Sum() + Map()
Just to show you another alternative, here’s one using the
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Method 3: Map() res = map(sum, data) print(list(res)) # [6, 15, 24]
map(function, iterable) function applies
function to each element in
iterable. As an alternative, you can also use list comprehension as shown in method 1 in this tutorial. In fact, Guido van Rossum, the creator of Python and Python’s benevolent dictator for life (BDFL), prefers list comprehension over the
- How to Average over a List of Lists in Python?
- How to Sum over all Columns of a List of Lists in Python?
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.