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 | Summation of list as tuple attribute

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

Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the summation of list as tuple attribute. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension + sum() This particular problem can be solved using list comprehension combined with the sum function in which we use sum function to find the sum of list as a tuple attribute and list comprehension to iterate through the list. 

Python3




# Python3 code to demonstrate
# Summation of list as tuple attribute
# using list comprehension + sum()
 
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + sum()
# Summation of list as tuple attribute
res = [(key, sum(lst)) for key, lst in test_list]
 
# print result
print("The list tuple attribute summation is : " + str(res))
 
 
Output : 

The original list : [(‘key1’, [3, 4, 5]), (‘key2’, [1, 4, 2]), (‘key3’, [9, 3])] The list tuple attribute summation is : [(‘key1’, 12), (‘key2’, 7), (‘key3’, 12)]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list, as the output list created by list comprehension will have the same number of elements as the input list. Additionally, the space required to store the input list and other program variables is negligible compared to the size of the input list.

Method #2: Using map + lambda + sum() The above problem can also be solved using the map function to extend the logic to the whole list and sum function can perform the similar task as the above method. 

Python3




# Python3 code to demonstrate
# Summation of list as tuple attribute
# using map() + lambda + sum()
 
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
# printing original list
print("The original list : " + str(test_list))
 
# using map() + lambda + sum()
# Summation of list as tuple attribute
res = list(map(lambda x: (x[0], sum(x[1])), test_list))
 
# print result
print("The list tuple attribute summation is : " + str(res))
 
 
Output : 

The original list : [(‘key1’, [3, 4, 5]), (‘key2’, [1, 4, 2]), (‘key3’, [9, 3])] The list tuple attribute summation is : [(‘key1’, 12), (‘key2’, 7), (‘key3’, 12)]

Time complexity: The time complexity of the given code is O(n), where n is the length of the input list.

Auxiliary space: The auxiliary space used by the given code is O(n), where n is the length of the input list. 

Method #3: Using starmap

First, the itertools module is imported to make the starmap function available. Then, the list of tuples is initialized and printed to show the original data.

Next, the starmap function is used to apply the sum function to the list attribute of each tuple in the list. The starmap function expects a function as its first argument, and then a list of tuples as its second argument. In this case, the lambda function is used as the first argument, and it takes two arguments: x and y. The lambda function returns a tuple containing the first element of the input tuple (x) and the sum of the second element (y). The starmap function applies this lambda function to each tuple in the input list, and returns an iterator of the results. This iterator is then converted to a list using the built-in list function.

Python3




from itertools import starmap
 
# Initialize the list of tuples
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
# Print the original list
print("The original list:", test_list)
 
# Use starmap to apply the sum function to the list attribute of each tuple
res = list(starmap(lambda x, y: (x, sum(y)), test_list))
 
# Print the result
print("The list tuple attribute summation:", res)
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list: [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])] The list tuple attribute summation: [('key1', 12), ('key2', 7), ('key3', 12)]

Time complexity:  O(n) , n is number of elements in all list of tuples
Auxiliary Space: O(n)

Method #4: Using a for loop

Use a for loop to iterate over the list of tuples. For each tuple, it computes the sum of the list using the sum() function and creates a new tuple with the key and the sum as the elements. This tuple is then appended to a new list, which is the final result.

Python3




# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
# printing original list
print("The original list : " + str(test_list))
 
# using for loop
# Summation of list as tuple attribute
res = []
for key, lst in test_list:
    total = sum(lst)
    res.append((key, total))
 
# print result
print("The list tuple attribute summation is : " + str(res))
 
 
Output
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])] The list tuple attribute summation is : [('key1', 12), ('key2', 7), ('key3', 12)]

Time complexity:  O(n), n is number of elements in all list of tuples
Auxiliary Space: O(n)

Method #5: Using a generator expression + sum()

In this implementation, we create a generator expression instead of a list comprehension by wrapping the expression in parentheses instead of brackets. The generator expression is then passed to the list() function to create a list of the results.

Python3




# Python3 code to demonstrate
# Summation of list as tuple attribute
# using generator expression + sum()
 
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
# printing original list
print("The original list : " + str(test_list))
 
# using generator expression + sum()
# Summation of list as tuple attribute
res = ((key, sum(lst)) for key, lst in test_list)
 
# print result
print("The list tuple attribute summation is : " + str(list(res)))
 
 
Output
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])] The list tuple attribute summation is : [('key1', 12), ('key2', 7), ('key3', 12)]

Time Complexity: O(n), where n is the length of the input list. 
Auxiliary Space: O(1), as we are not using any additional data structures that depend on the size of the input list.

Method#6: Using Recursive method.

This implementation uses recursion to iterate through each tuple in the test_list. The base case is when i is greater than or equal to the length of test_list. If i is less than the length of test_list, it calculates the sum of the second element of the tuple and creates a new tuple with the same key and the sum as the value. It then concatenates this tuple with the result of the recursive call with i incremented by 1. The final result is returned as a list of tuples.

Python3




def tuple_attribute_sum_recursive(test_list, i=0):
    if i >= len(test_list):
        return []
    else:
        total = sum(test_list[i][1])
        return [(test_list[i][0], total)] + tuple_attribute_sum_recursive(test_list, i+1)
 
# initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
# printing original list
print("The original list : " + str(test_list))
 
# using recursive function
# Summation of list as tuple attribute
res = tuple_attribute_sum_recursive(test_list)
 
# print result
print("The list tuple attribute summation is : " + str(res))
 
 
Output
The original list : [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])] The list tuple attribute summation is : [('key1', 12), ('key2', 7), ('key3', 12)]

The time complexity of the recursive implementation of tuple_attribute_sum_recursive function is O(n), where n is the length of the test_list. This is because we visit each element of the test_list exactly once, and for each element, we do a constant amount of work, including a recursive call with the index incremented by 1.

The space complexity of the recursive implementation is also O(n), where n is the length of the test_list. This is because at any point during the recursion, there will be at most n recursive calls on the call stack, each of which stores a constant amount of information, including the current index and the res list.

Method #4: Using numpy.sum()

This method uses numpy to sum the list in each tuple of the list. The numpy.sum() function is used to sum the array of each tuple.

Note: numpy.sum() can only sum 1D and 2D arrays, so we need to flatten the list inside the tuple first.

Python3




import numpy as np
 
#initializing list
test_list = [('key1', [3, 4, 5]), ('key2', [1, 4, 2]), ('key3', [9, 3])]
 
#printing original list
print("The original list : " + str(test_list))
 
#using numpy.sum() to sum the list inside each tuple
#Summation of list as tuple attribute
res = [(key, np.sum(np.array(lst).flatten())) for key, lst in test_list]
 
#print result
print("The list tuple attribute summation is : " + str(res))
 
 

Output:

The original list : [(‘key1’, [3, 4, 5]), (‘key2’, [1, 4, 2]), (‘key3’, [9, 3])]
The list tuple attribute summation is : [(‘key1’, 12), (‘key2’, 7), (‘key3’, 12)]

Time complexity: O(n), where n is the length of the input list.

Auxiliary space: O(n), where n is the length of the input list, as the output list created by list comprehension will have the same number of elements as the input list. Additionally, the space required to store the input list, numpy array, and other program variables is negligible compared to the size of the input list.



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 | 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 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 - 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 - List of dictionaries all values Summation
    Given a list of dictionaries, extract all the values summation. Input : test_list = [{"Apple" : 2, "Mango" : 2, "Grapes" : 2}, {"Apple" : 2, "Mango" : 2, "Grapes" : 2}] Output : 12 Explanation : 2 + 2 +...(6-times) = 12, sum of all values. Input : test_list = [{"Apple" : 3, "Mango" : 2, "Grapes" : 2
    5 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 | Add tuple to front of list
    Sometimes, while working with Python list, we can have a problem in which we need to add a new tuple to existing list. Append at rear is usually easier than addition at front. Let's discuss certain ways in which this task can be performed. Method #1 : Using insert() This is one of the way in which t
    7 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 | Accumulative index summation in tuple list
    Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using
    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