Python | Position Summation in List of Tuples
Sometimes the data that we receive, is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the sum of each index of tuple for cumulation. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension
This is the most naive method to perform this particular task, in this method we compute the summation of each index of all the possible indices of the tuple.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
The original list is : [(1, 6), (3, 4), (5, 8)] The position summation of tuples : (9, 18)
Method #2 : Using
zip() + sum()
This is the most elegant and pythonic way to perform this particular task. In this we combine all the indices of the element using
zip() and the performance of summation using sum function.
The original list is : [(1, 6), (3, 4), (5, 8)] The position summation of tuples : [9, 18]