

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
It can be achieved in the following ways.
Using for loop and zip
Using the for loop we loop through each item and apply zip function to gather the values from each column. Then we apply the sum function and finally get the result into a new tuple.
Example
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))
Output
Running the above code gives us the following 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 without using for loop and using map function instead.
Example
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))
Output
Running the above code gives us the following 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)]
- Related Questions & Answers
- Summation of tuples in list in Python
- Combining tuples in list of tuples in Python
- Python Grouped summation of tuple list¶
- Grouped summation of tuple list in Python
- Python – Summation of consecutive elements power
- Count tuples occurrence in list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Addition of tuples in Python
- Summation of list as tuple attribute in Python
- Alternate element summation in list (Python)
- Python – Dual Tuple Alternate summation
- Accessing Values of Tuples in Python
- How to split Python tuples into sub-tuples?
- Python program to find Tuples with positive elements in List of tuples
- Remove tuples from list of tuples if greater than n in Python
Advertisements