Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Column summation of tuples
Python has extensive availability of various libraries and functions which make it so popular for data analysis. We may get a need to sum the values in a single column for a group of tuples for our analysis. So in this program we are adding all the values present at the same position or same column in a series of tuples.
Column summation involves adding corresponding elements from tuples at the same positions. For example, if we have tuples (3, 92) and (25, 62), the column summation would be (28, 154).
Using List Comprehension and zip()
Using list comprehension with the zip() function, we can gather values from each column and apply the sum() function to get the result as a new tuple ?
data = [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]]
print("The list of tuples: " + str(data))
# Using list comprehension + zip()
result = [tuple(sum(m) for m in zip(*n)) for n in zip(*data)]
print("Column summation of tuples: " + str(result))
The list of tuples: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
Using map() and zip()
We can achieve the same result using the map() function instead of list comprehension for a more functional programming approach ?
data = [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]]
print("The list of tuple values: " + str(data))
# Using zip() + map()
result = [tuple(map(sum, zip(*n))) for n in zip(*data)]
print("Column summation of tuples: " + str(result))
The list of tuple values: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
How It Works
The operation works in these steps:
-
zip(*data)transposes the nested structure, grouping corresponding tuples -
zip(*n)pairs corresponding elements from each tuple -
sum()adds the paired elements together -
tuple()converts the result back to a tuple format
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | Good | Fast | General use |
| map() + zip() | Moderate | Slightly faster | Functional programming style |
Conclusion
Both approaches effectively perform column summation of tuples using Python's built-in functions. The list comprehension method offers better readability, while the map() approach follows functional programming principles.
