Fundamentals 5 min read

Three Clever Ways to Sum Columns in a 2D Python List

This article demonstrates three efficient Python techniques—list unpacking, NumPy aggregation, and functional reduction—to sum corresponding elements across sub‑lists in a two‑dimensional list, complete with code examples and visual explanations for beginners and seasoned developers alike.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Three Clever Ways to Sum Columns in a 2D Python List

1. Introduction

A fan asked how to sum each column of a regular two‑dimensional Python list. The naïve approach uses separate accumulator variables for each column, which becomes unwieldy when the sub‑lists contain many elements.

lst = [[1, 2, 3, 4], [1, 5, 1, 2], [2, 3, 4, 5], [5, 3, 1, 3]]
s1 = 0
s2 = 0
s3 = 0
s4 = 0
for i in lst:
    s1 += i[0]
    s2 += i[1]
    s3 += i[2]
    s4 += i[3]
print(list([s1, s2, s3, s4]))

This works but is not scalable.

2. Solutions

Solution by Yuliang

Using list unpacking with zip to transpose the matrix and sum each column.

lst = [[1, 2, 3, 4], [1, 5, 1, 2], [2, 3, 4, 5], [5, 3, 1, 3]]
[print(sum(i) for i in zip(*lst))]

Solution by Daler

Leveraging NumPy to compute sums along both axes.

import numpy as np

lst = [[1, 2, 3, 4], [1, 5, 1, 2], [2, 3, 4, 5], [5, 3, 1, 3]]
list1 = np.sum(lst, axis=0)  # column‑wise sum
list2 = np.sum(lst, axis=1)  # row‑wise sum
print(list1)
print(list2)

Solution by Moon God

Applying functools.reduce with map and a lambda to aggregate columns.

from functools import reduce

lst = [[1, 2, 3, 4],
       [1, 5, 1, 2, 6],
       [2, 3, 4, 5],
       [5, 3, 1, 3]]
print(list(reduce(lambda x, y: map(lambda i, j: i + j, x, y), lst)))

3. Conclusion

The three methods—list unpacking with zip, NumPy aggregation, and functional reduction—provide concise and scalable ways to sum corresponding elements of sub‑lists in a 2D list. Choose the approach that best fits your project’s dependencies and readability preferences.

reducedata-processinglist-unpackinglist-sum
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.