Open In App

Summation Matrix columns – Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13].

Using numpy.sum()

numpy.sum() is a highly optimized function from the numpy library that efficiently handles mathematical operations on matrices . It can directly sum the columns of a matrix by specifying the axis as 0.

Python
import numpy as np
a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]

a = np.array(a) # Converting `a` to numpy array
res = np.sum(a, axis=0).tolist()
print(res)

Output
[13, 13, 13]

Explanation: np.sum(a, axis=0) calculates sum the elements of each column. Then result is converted back to a list with tolist() .

Using list comprehension

List comprehension is a concise way of generating lists in Python. When summing columns, we use the zip(*a) technique to transpose the matrix and iterate over each column to apply sum().

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

res = [sum(idx) for idx in zip(*a)]
print(res)

Output
[13, 13, 13]

Explanation: This code transposes the matrix using zip(*a), sums each column with sum(idx) and stores the results in a list.

Using itertools.starmap()

itertools.starmap() applies a function to the items in an iterable. When used with sum() and zip(*a), it sums the columns in a similar way to the list comprehension approach.

Python
import itertools

a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
res = list(itertools.starmap(lambda *args: sum(args), zip(*a)))
print(res)

Output
[13, 13, 13]

Explanation: itertools.starmap() apply the sum() function to each transposed column from zip(*a). It sums the elements of each column and stores the results in a list.

Using for loop

A traditional for loop iterates over the transposed matrix using zip(*a) and sums the elements in each column manually.

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

for col in zip(*a):
    res.append(sum(col))
print(res)

Output
[13, 13, 13]

Explanation: This code transposes the matrix with zip(*a), sums each column in a for loop and appends the results to a list.



Next Article

Similar Reads