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 - Skew Nested Tuple Summation
Next article icon

Python – Absolute Tuple Summation

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 performed.

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

Method #1 : Using sum() + list comprehension + abs() The combination of above functions can be used to solve this problem. In this, we perform the task of computing sum using sum(), abs() for absolute values, and list comprehension to iterate through the list and inside each tuple, generator expression is used to iterate. 

Python3




# Python3 code to demonstrate working of
# Absolute Tuple Summation
# Using sum() + list comprehension + abs()
 
# initializing list
test_list = [(7, -8), (-5, -6), (-7, 2), (6, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Absolute Tuple Summation
# Using sum() + list comprehension + abs()
res = [sum([abs(ele) for ele in sub]) for sub in test_list]
 
# printing result
print("The absolute sum list: " + str(res))
 
 
Output : 
The original list is : [(7, -8), (-5, -6), (-7, 2), (6, 8)] The absolute sum list: [15, 11, 9, 14]

  Method #2 : Using list comprehension + sum() + map() The combination of above functions offer an alternative to solve this problem. In this, we perform the task of computing sum of entire tuple elements using map() rather than generator expression. 

Python3




# Python3 code to demonstrate working of
# Absolute Tuple Summation
# Using list comprehension + sum() + map()
 
# initializing list
test_list = [(7, -8), (-5, -6), (-7, 2), (6, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Absolute Tuple Summation
# Using list comprehension + sum() + map()
res = [sum(map(abs, ele)) for ele in test_list]
 
# printing result
print("The absolute sum list: " + str(res))
 
 
Output : 
The original list is : [(7, -8), (-5, -6), (-7, 2), (6, 8)] The absolute sum list: [15, 11, 9, 14]

Method #3 : Using recursion+abs()

In the above example, the given list is test_list = [(-7, -8), (-5, -6)]. In the first iteration of the loop, the absolute values of -7 and -8 are taken and stored in the abs_tup variable as (7, 8). The sum of these absolute values is 15, which is appended to the result list. In the second iteration, the absolute values of -5 and -6 are taken and stored in the abs_tup variable as (5, 6). The sum of these absolute values is 11, which is appended to the result list. Finally, the result list is returned as the output.

Python3




def absolute_tuple_summation(test_list):
    result = []
    for tup in test_list:
        # absolute values of tuple elements
        abs_tup = tuple(abs(num) for num in tup)
        # sum of absolute values of tuple elements
        abs_sum = sum(abs_tup)
        result.append(abs_sum)
    return result
# example
test_list = [(-7, -8), (-5, -6)]
result = absolute_tuple_summation(test_list)
print(result)
 
 
Output
[15, 11]

Time complexity:  O(n*m)

Auxiliary Space:  O(n)

Method #4 : Using nested for loops

Approach

  1. Initiated for loop to traverse list of tuples
  2. Initiate another for loop inside above loop to traverse each tuple
  3. With in for loop if tuple element is less than zero multiply with -1 and find the sum of elements of tuple
  4. Add the sum to output list
  5. Display output list

Python3




# Python3 code to demonstrate working of
# Absolute Tuple Summation
# initializing list
test_list = [(7, -8), (-5, -6), (-7, 2), (6, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Absolute Tuple Summation
res=[]
for i in test_list:
    s=0
    for j in i:
        if(j<0):
            s+=(-1)*j
        else:
            s+=j
    res.append(s)
# printing result
print("The absolute sum list: " + str(res))
 
 
Output
The original list is : [(7, -8), (-5, -6), (-7, 2), (6, 8)] The absolute sum list: [15, 11, 9, 14]

Time Complexity : O(n*m) n – length of tuples list m- length of each tuple

Auxiliary Space : O(n)

Method #5 : Using numpy:

Algorithm:

  1. Initialize the test_list with tuples.
  2. Use np.abs() function to calculate the absolute values of the tuples in the test_list.
  3. Use np.sum() function to calculate the sum of absolute values of each tuple across the rows (axis=1) of the array.
  4. Assign the result to the variable ‘res’.
  5. Print the original list an

Python3




import numpy as np
# initializing list
test_list = [(7, -8), (-5, -6), (-7, 2), (6, 8)]
res = np.abs(test_list).sum(axis=1)
# printing original list
print("The original list is : " + str(test_list))
# printing result
print("The absolute sum list: " + str(res))
#This code is contributed by Jyothi Pinjala.
 
 

Output:

The original list is : [(7, -8), (-5, -6), (-7, 2), (6, 8)]
The absolute sum list: [15 11  9 14]

Time Complexity:
The time complexity of this code is O(n), where n is the length of the test_list. The np.abs() and np.sum() functions have a complexity of O(n).
Auxiliary Space:
The space complexity of this code is O(n), where n is the length of the test_list. This is due to the creation of the numpy array ‘res’ which stores the absolute sum of each tuple.

Method #6 : Using lambda function and map()

  1. Initialize the list of tuples.
  2. Define a lambda function that takes a tuple as input and returns the absolute sum of its elements.
  3. Use the map() function to apply the lambda function to each tuple in the list, and store the results in a new list.
  4. Print the original list and the resulting list of absolute sums.

Python3




# Python3 code to demonstrate working of
# Absolute Tuple Summation
 
# initializing list
test_list = [(7, -8), (-5, -6), (-7, 2), (6, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using lambda function and map()
abs_sum = list(map(lambda tup: sum(map(abs, tup)), test_list))
 
# printing result
print("The absolute sum list: " + str(abs_sum))
 
 
Output
The original list is : [(7, -8), (-5, -6), (-7, 2), (6, 8)] The absolute sum list: [15, 11, 9, 14]

Time complexity: O(n)
Auxiliary space: O(n)



Next Article
Python - Skew Nested Tuple Summation
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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 - 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
  • 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 | 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 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 - 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 | Nested Tuples Subtraction
    Sometimes, while working with records, we can have a problem in which we require to perform index-wise subtraction of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuple. Let’s discuss certain ways in which this problem can be solved.  Metho
    7 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 | 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
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