Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Summation of tuples in list in Python
When working with a list of tuples, you often need to calculate the total sum of all elements across all tuples. Python provides several approaches to achieve this using map(), sum(), and other methods.
A list of tuples contains tuples enclosed in a list, where each tuple can hold multiple numeric values. The map() function applies a given operation to every item in an iterable, while sum() adds all elements in an iterable.
Using map() and sum()
The most concise approach combines map() and sum() to first sum each tuple, then sum all results ?
my_list = [(11, 14), (54, 56), (98, 0), (13, 76)]
print("The list is:")
print(my_list)
my_result = sum(map(sum, my_list))
print("The summation of tuples in a list is:")
print(my_result)
The list is: [(11, 14), (54, 56), (98, 0), (13, 76)] The summation of tuples in a list is: 322
Using Nested Loops
An alternative approach uses nested loops for more explicit control ?
my_list = [(11, 14), (54, 56), (98, 0), (13, 76)]
total_sum = 0
for tuple_item in my_list:
for element in tuple_item:
total_sum += element
print("Total sum using nested loops:", total_sum)
Total sum using nested loops: 322
Using List Comprehension
You can flatten the tuples and sum all elements in one line ?
my_list = [(11, 14), (54, 56), (98, 0), (13, 76)]
result = sum([element for tuple_item in my_list for element in tuple_item])
print("Sum using list comprehension:", result)
Sum using list comprehension: 322
How It Works
In the sum(map(sum, my_list)) approach:
- Inner
sumcalculates the sum of each tuple: (11+14)=25, (54+56)=110, (98+0)=98, (13+76)=89 -
map()appliessumto each tuple, creating an iterator: [25, 110, 98, 89] - Outer
sumadds all these results: 25+110+98+89=322
Conclusion
Use sum(map(sum, my_list)) for the most concise solution. For better readability, use nested loops or list comprehension depending on your preference and code style requirements.
