
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 −
Example
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)
Output
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)]
Explanation
- 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.
Advertisements