- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Summation of list as tuple attribute in Python
When it is required to get the summation of a list of tuple, the list comprehension and the 'sum' method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
The 'sum' method is used to add the elements of an iterable, where the iterable is passed as an argument to the method.
Below is a demonstration for the same −
my_list = [('Hi', [45, 67, 21]), ('There', [45, 32, 1]), ('Jane', [59, 13])] print("The list is : ") print(my_list) my_result = [(key, sum(lst)) for key, lst in my_list] print("The list of tuple after summation is : ") print(my_result)
The list is : [('Hi', [45, 67, 21]), ('There', [45, 32, 1]), ('Jane', [59, 13])] The list of tuple after summation is : [('Hi', 133), ('There', 78), ('Jane', 72)]
- A list of tuple is defined, and is displayed on the console.
- It is iterated over, using list comprehension, and every integer in the list of tuple is added, and it is converted to a list.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
- Python Grouped summation of tuple list¶
- Grouped summation of tuple list in Python
- Maximum value in record list as tuple attribute in Python
- Python – Dual Tuple Alternate summation
- Summation of tuples in list in Python
- Alternate element summation in list (Python)
- Flatten tuple of List to tuple in Python
- Why python returns tuple in list instead of list in list?
- Raise elements of tuple as power to another tuple in Python
- Dictionary to list of tuple conversion in Python
- Python – Cross Pairing in Tuple List
- Maximum element in tuple list in Python
- Convert a list into tuple of lists in Python
- Python - Column summation of tuples
- List vs tuple vs dictionary in Python