Three Elegant Python Tricks to Sum Columns in a 2D List
This article presents three concise Python solutions—including list unpacking, NumPy aggregation, and a functional‑programming approach—to efficiently sum corresponding elements across sublists in a two‑dimensional list, complete with code examples and visual output.
1. Introduction
A fan named dcpeng asked in a Python community how to sum the columns of a two‑dimensional list, as shown in the figure below.
The initial code works but requires a separate accumulator variable for each column, which becomes unwieldy when the sublists contain many elements.
2. Implementation
Solution by Yuliang
Yuliang provided a compact solution using list unpacking:
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
Building on an earlier suggestion to use NumPy, Daler wrote:
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
Moon God offered a more advanced functional solution using built‑in functions and a lambda expression:
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. Summary
The three approaches demonstrate how to efficiently sum corresponding elements of each sublist in a regular 2D list using pure Python, NumPy, and functional programming techniques, providing clear code examples that help Python learners solve this common data‑processing task.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
