Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Column summation of tuples
Next article icon

Python – Tuple Matrix Columns Summation

Last Updated : 09 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [[(4, 5), (1, 2)], [(2, 4), (4, 6)]] 
Output : [(6, 9), (5, 8)] 

Input : test_list = [[(4, 5), (1, 2), (6, 7)]] 
Output : [(4, 5), (1, 2), (6, 7)]

Method #1 : Using list comprehension + zip() + sum() The combination of above functions can be used to solve this problem. In this, we perform the task of sum using sum() and zip() is used to perform column wise pairing of all elements. 

step by step approach of the program:

  1. Define a nested list test_list containing tuples of integers.
  2. Print the original list.
  3. Create a list comprehension to iterate over the columns of the matrix.
  4. Use the zip() function to group the tuples in each column together.
  5. Apply the sum() function to each group of tuples to get the sum of the elements in that column.
  6. Wrap the result of the sum() function in a tuple using the tuple() constructor.
  7. Append the tuple of column sums to the result list for each column.
  8. Print the result list.

Python3




# Python3 code to demonstrate working of
# Tuple Matrix Columns Summation
# Using list comprehension + zip() + sum()
 
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Tuple Matrix Columns Summation
# Using list comprehension + zip() + sum()
res = [tuple(sum(ele) for ele in zip(*i)) for i in zip(*test_list)]
 
# printing result
print("Tuple matrix columns summation : " + str(res))
 
 
Output : 
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]] Tuple matrix columns summation : [(9, 9), (11, 13)]

Time complexity: O(n^2) where n is the number of elements in the input list.
Auxiliary space: O(n^2) as well, where n is the number of elements in the input list.

Method #2 : Using map() + list comprehension + zip() The combination of above functions can be used to solve this problem. In this, we perform the task of extension of sum() using map() and rest of the functionalities are performed similar to above method. 

Python3




# Python3 code to demonstrate working of
# Tuple Matrix Columns Summation
# Using map() + list comprehension + zip()
 
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Tuple Matrix Columns Summation
# Using map() + list comprehension + zip()
res = [tuple(map(sum, zip(*ele))) for ele in zip(*test_list)]
 
# printing result
print("Tuple matrix columns summation : " + str(res))
 
 
Output : 
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]] Tuple matrix columns summation : [(9, 9), (11, 13)]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.  map() + list comprehension + zip() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

Method #3: Using NumPy library

This program imports the NumPy library and converts a given matrix (test_list) into a NumPy array. It then calculates the column-wise sum of the array using the np.sum() function and returns the result as a tuple. Finally, it prints the tuple containing the column-wise sums of the matrix.

Python3




import numpy as np
 
# initializing matrix
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
 
# converting matrix to NumPy array
arr = np.array(test_list)
 
# calculating column-wise sum
res = tuple(map(tuple, np.sum(arr, axis=0)))
 
# printing result
print("Tuple matrix columns summation : " + str(res))
 
 

OUTPUT:

Tuple matrix columns summation : ((9, 9), (11, 13))

The time complexity of the code snippet would be O(n^2), where n is the number of elements in the matrix. 

The auxiliary space complexity of the code would be O(n^2) as well, because we are creating a NumPy array to store the matrix elements.

Method #4: Using a for loop and nested loops to iterate over the matrix and sum the columns.

In this method, we use a for loop to iterate over the columns of the matrix. For each column, we initialize a tuple col_sum with zeros, and then use nested loops to iterate over the rows and add the values in each row to col_sum. We use the zip() function to group the values in the same position in each row together, and the map() function to sum these values. Finally, we append col_sum to the result list.

Step-by-step approach:

  • Initialize an empty result list res.
  • Iterate over each column using a for loop with range() function and the number of columns num_cols.
  • For each column, we initialize a tuple col_sum with zeros using (0, 0).
  • Iterate over each row using a nested for loop with range() function and the number of rows num_rows.
  • For each row, we use the zip() function to group the values in the same position in each row together, and the map() function to sum these values using the sum() function. We add these values to col_sum using the tuple() function to convert the result to a tuple.
  • After iterating over all rows, we append col_sum to the result list res.
  • After iterating over all columns, we have the required result stored in res.
  • We print the result using the print() function and concatenation of string and the list.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Tuple Matrix Columns Summation
# Using for loop and nested loops
 
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Tuple Matrix Columns Summation
# Using for loop and nested loops
num_rows = len(test_list)
num_cols = len(test_list[0])
res = []
for j in range(num_cols):
    col_sum = (0, 0)
    for i in range(num_rows):
        col_sum = tuple(map(sum, zip(col_sum, test_list[i][j])))
    res.append(col_sum)
 
# printing result
print("Tuple matrix columns summation : " + str(res))
 
 
Output
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]] Tuple matrix columns summation : [(9, 9), (11, 13)]

The time complexity of this method is O(n^2), where n is the number of rows or columns in the matrix.
The auxiliary space complexity is O(n), since we need to store the result list.

Method #5: Using itertools module

Uses the itertools module to iterate over the columns of the matrix and sum them. 

Step-by-step approach:

  • Import the itertools module.
  • Initialize an empty list to store the column sums.
  • Iterate over the columns of the matrix using the zip() function and the * operator to unpack the tuples.
  • Use the sum() function to calculate the sum of each column and append it to the list of column sums.
  • Convert the list of column sums to a tuple and print it as the result.

Python3




import itertools
 
# initializing matrix
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
 
# calculating column-wise sum using itertools
col_sums = []
for col in itertools.zip_longest(*test_list, fillvalue=(0, 0)):
    col_sum = sum([x[0] for x in col]), sum([x[1] for x in col])
    col_sums.append(col_sum)
 
# converting column sums to tuple
res = tuple(col_sums)
 
# printing result
print("Tuple matrix columns summation : " + str(res))
 
 
Output
Tuple matrix columns summation : ((9, 9), (11, 13))

Time complexity: O(nm), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary space: O(m), where m is the number of columns in the matrix.

Method 6: Using reduce() function from the functools module and lambda function

  1. Import the reduce() function from the functools module.
  2. Initialize the test_list with a nested list of tuples.
  3. Print the original list using the print() function.
  4. Use the zip() function to group the tuples from the same column of the matrix together.
  5. Use a list comprehension to iterate over the zipped list of columns and apply the reduce() function with a lambda function that takes two tuples and adds their corresponding elements.
  6. Convert the resulting tuple back to a tuple and append it to the res list using tuple comprehension.
  7. Print the res list containing the sum of columns of the matrix.

Python3




# Python3 code to demonstrate working of
# Tuple Matrix Columns Summation
# Using reduce() and lambda
 
from functools import reduce
 
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Tuple Matrix Columns Summation
# Using reduce() and lambda
res = [tuple(reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), i))
       for i in zip(*test_list)]
 
# printing result
print("Tuple matrix columns summation : " + str(res))
 
 
Output
The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]] Tuple matrix columns summation : [(9, 9), (11, 13)]

The time complexity is O(mn), where m is the number of rows and n is the number of columns in the matrix.

The space complexity is O(n), where n is the number of columns in the matrix. 



Next Article
Python | Column summation of tuples
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Summation Matrix columns - Python
    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 hi
    2 min read
  • Python | Column summation of tuples
    Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let's discuss certain ways in which this can be done. Method
    7 min read
  • Python | Matrix True Summation
    Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Let's discuss certain way
    8 min read
  • Python | Summation of Kth Column of Tuple List
    Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task ca
    7 min read
  • Python - Absolute Tuple Summation
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform the summation of absolute values of intermediate tuple elements. This kind of problem can have application in many domains such as web development. Let's discuss certain ways in which this task can be perf
    6 min read
  • Python - Cross tuple summation grouping
    Sometimes, while working with Python tuple records, we can have a problem in which we need to perform summation grouping of 1st element of tuple pair w.r.t similar 2nd element of tuple. This kind of problem can have application in day-day programming. Let's discuss certain ways in which this task ca
    7 min read
  • Python - Summation of kth column in a matrix
    Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Us
    8 min read
  • Python | Summation of tuples in list
    Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
    7 min read
  • Python - Skew Nested Tuple Summation
    Given a Tuple, nesting at 2nd position, return summation of 1st elements. Input : test_tup = (5, (6, (1, (9, None)))) Output : 21 Explanation : 9 + 6 + 5 + 1 = 21. Input : test_tup = (5, (6, (1, None))) Output : 12 Explanation : 1 + 6 + 5 = 12. Method #1: Using infinite loop In this, we perform get
    6 min read
  • Python - Dual Tuple Alternate summation
    Given dual tuple, perform summation of alternate elements, i.e of indices alternatively. Input : test_list = [(4, 1), (5, 6), (3, 5), (7, 5)] Output : 18 Explanation : 4 + 6 + 3 + 5 = 18, Alternatively are added to sum. Input : test_list = [(4, 1), (5, 6), (3, 5)] Output : 13 Explanation : 4 + 6 + 3
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences