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 | Summation of tuples in list
Next article icon

Python | Column summation of tuples

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

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 #1 : Using zip() + list comprehension This problem can be resolved using the list comprehension which could perform the column summation logic and zip function is used to bind the elements as a result and also at the time of vertical summation. 

Python3




# Python3 code to demonstrate
# column summation of list of tuple
# using list comprehension + zip()
 
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + zip()
# column summation of list of tuple
res = [tuple(sum(j) for j in zip(*i))
            for i in zip(*test_list)]
 
# print result
print("The summation of columns of tuple list : " + str(res))
 
 
Output : 
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]] The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]

Time complexity: O(nm), where n is the number of sublists in the input list and m is the length of the sublists (assuming that the length of all sublists is the same).
Auxiliary space: O(nm), since it creates a new list of tuples with the same dimensions as the input list.

Method #2 : Using zip() + map() The task of binding the column elements can also be performed using the map function and the zip function performs the task of binding the summation tuples. Both logics bound by list comprehension. 

Python3




# Python3 code to demonstrate
# column summation of list of tuple
# using zip() + map()
 
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using zip() + map()
# column summation of list of tuple
res = [tuple(map(sum, zip(*i)))
      for i in zip(*test_list)]
 
# print result
print("The summation of columns of tuple list : " + str(res))
 
 
Output : 
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]] The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]

Time Complexity : O(m*n), where m is the number of rows and n is the number of columns in the list of tuples.

Auxiliary Space : O(n), where n is the number of columns in the list of tuples.

Method #3: Using for loop and append()

Using a for loop and append() method to iterate through the tuples in each list and sum up the elements in each column.

Python3




test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# get the length of the inner tuples
n = len(test_list[0][0])
 
# initialize the result list with zeros
res = [(0,)*n for _ in range(len(test_list[0]))]
 
# iterate through the tuples in each list and sum up the elements in each column
for l in test_list:
    for i, tpl in enumerate(l):
        res[i] = tuple(x+y for x,y in zip(res[i], tpl))
 
# print the result
print("The summation of columns of tuple list : ", res)
 
 
Output
The summation of columns of tuple list :  [(4, 11), (3, 12), (15, 7)]

Time Complexity: O(n^2), where n is the number of elements in the longest inner tuple. This is because the code uses two nested loops to iterate through the tuples in the input list.
Auxiliary Space: O(n), where n is the number of elements in the longest inner tuple. This is because the code creates a new tuple for each column in the input list to store the sum of the elements in that column.

Method #4: Using NumPy library

NumPy is a popular library for numerical computations in Python. It provides many efficient and convenient functions for working with arrays, matrices, and other data structures. We can use the NumPy library to solve the given 

step-by-step explanation of the program:

  1. First, the NumPy library is imported using the statement import numpy as np.
  2. A list test_list is defined, which contains two lists of tuples. Each tuple contains two integers.
  3. The list test_list is converted to a NumPy array using the function np.array(). The resulting NumPy array has dimensions 2×3, since there are two lists of tuples, and each list contains three tuples.
  4. The sum() method of NumPy arrays is used to sum the elements along the first axis (columns) of the array. The resulting array has dimensions 1×3, since there are three columns in the original array.
  5. The resulting array is assigned to the variable res.
  6. Finally, the print() function is used to print a string that describes the result. The variable res is included in the string using an f-string, which allows variables to be inserted into strings using curly braces {}.

Python3




import numpy as np
 
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# convert the list to a NumPy array
arr = np.array(test_list)
 
# sum the elements along the first axis (columns)
res = arr.sum(axis=0)
 
# print the result
print("The summation of columns of tuple list : ", res)
 
 

OUTPUT:

The summation of columns of tuple list :  [[ 4 11] [ 3 12] [15  7]]

Time complexity: O(n^2), where n is the length of the inner tuples. This is because we need to iterate over all the elements in the input list and perform a constant number of operations (addition) on each element.

Auxiliary space: O(n), where n is the length of the inner tuples. This is because we need to create a new array of zeros to initialize the result, and a new array to store the transposed input. However, these arrays have a fixed size that depends only on the length of the inner tuples, so the space complexity is O(n).

Method 5: Using the built-in function reduce() from the functools module. 

Step-by-step approach:

  1. First, import the reduce() function from the functools module.
  2. Then, initialize the list of tuples test_list.
  3. Next, use the zip() function to group the tuples by their index, i.e., all the first tuples will be grouped together, all the second tuples will be grouped together, and so on. We use the * operator to unpack the test_list list and pass it as arguments to the zip() function.
  4. Use the map() function to apply a lambda function to each group of tuples. The lambda function takes a group of tuples as input and uses the reduce() function to sum the tuples element-wise. The result of each reduce() operation is a tuple of two elements that represent the sums of the corresponding elements of the input tuples. Finally, the lambda function returns this tuple.
  5. The map() function returns an iterator of tuples. Convert this iterator to a list using the list() function.
  6. Finally, we print the resulting list of tuples.

Python3




# import reduce function from functools module
from functools import reduce
 
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using reduce() and lambda function to sum the tuples
res = list(map(lambda x: tuple(reduce(lambda a, b: (a[0] + b[0], a[1] + b[1]), x)), zip(*test_list)))
 
# print result
print("The summation of columns of tuple list : " + str(res))
 
 
Output
The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]] The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]

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



Next Article
Python | Summation of tuples in list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python - Tuple Matrix Columns Summation
    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 : tes
    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 | 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 | Summation of two list of tuples
    Sometimes, while working with Python records, we can have a problem in which we need to perform cross-summation of list of tuples. This kind of application is popular in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip
    6 min read
  • Python - Summation of tuple dictionary values
    Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Let’s discuss certain ways in which this particular problem can be solved. Method #1: Using
    4 min read
  • Python | Grouped summation of tuple list
    Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small cha
    10 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 Unique elements
    This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence it’s knowledge is good to have.  Method 1 : Naive method + sum()  In naive method, we simply t
    5 min read
  • 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
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