Open In App

Python – Ways to sum list of lists and return sum list

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with nested lists (lists of lists), we may need to compute the sum of corresponding elements across all inner lists. In this article, we will see how Python provides multiple methods to perform this task. The most common and efficient way to sum up a list of lists is by using zip() combined list comprehension.

Python
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = [sum(x) for x in zip(*a)]
print(b)  

Output
[12, 15, 18]
  • zip(*lists) unpacks the inner lists and groups their corresponding elements together: [(1, 4, 7), (2, 5, 8), (3, 6, 9)].
  • sum(x) computes the sum of each tuple.
  • The result is a list containing the sum of corresponding elements: [12, 15, 18].

Let’s explore some other methods and see different ways to sum list of lists and return sum list in Python.

Using map() and sum()

map() function can be used to apply sum() to each group of corresponding elements.

Python
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

b = list(map(sum, zip(*a)))
print(b) 

Output
[12, 15, 18]

Explanation:

  • zip(*lists) groups corresponding elements across all lists.
  • map(sum, ...) applies the sum() function to each group.
  • list() converts the result back to a list.

Using NumPy

If we are working with large lists or require more advanced numerical operations, NumPy is a powerful library for such tasks.

Python
import numpy as np

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = np.sum(a, axis=0).tolist()
print(b) 

Output
[12, 15, 18]

Explanation:

  • np.sum() computes the sum along the specified axis.
  • axis=0 sums across the rows (corresponding elements).
  • .tolist() converts the result back to a Python list.

Using Loops

For a more manual approach, we can iterate through the lists using a for loop and sum the corresponding elements.

Python
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Initialize a result list with zeros
b = [0] * len(a[0])

# Add elements from each list
for l in a:
    for i in range(len(l)):
        b[i] += l[i]

print(b)  

Output
[12, 15, 18]

Explanation:

  • A result list sum_list is initialized with zeros.
  • A nested loop iterates through each list and its elements, adding corresponding values.


Next Article

Similar Reads