Python | Summing positions in a list of tuples

Python Methods and Functions

Method # 1: Using List Comprehension
This is the most naive method to accomplish this particular task, in this method we compute the sum of each index of all possible indexes of the tuple.

# Python3 demo code
# summing positions in the list of tuples
# using comprehension list

 
# initializing list

test_list = [( 1 , 6 ), ( 3 , 4 ), ( 5 , 8 )]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# Summing position in the list of tuples
# using comprehension list

res = sum (i [ 0 ] for i in test_list), sum (i [ 1 ] for i in test_list)

 
# print summary

print ( "The position summation of tuples :" + str (res))

Output:

 The original list is: [(1, 6), (3, 4), (5, 8)] The position summation of tuples: (9, 18) 

Method # 2: Using zip () + sum ()
This the most elegant and pythonic way to accomplish this particular task. In this we concatenate all the indices of an element using zip () and perform the summation using the sum function.

# Python3 demo code
# summing positions in the list of tuples
# using zip () + sum ()

 
# initializing list

test_list = [( 1 , 6 ), ( 3 , 4 ), ( 5 , 8 )]

  
# print original list

print ( "The original list is:" + str (test_list))

 
# Summing the position in the list of tuples
# using zip () + sum ()

res = [ sum (i) for i in zip ( * test_list)]

 
# print amounts coding

print ( "The position summation of tuples : " + str (res))

Output:

 The original list is: [(1, 6), (3, 4), (5, 8)] The position summation of tuples: [9, 18] 




Get Solution for free from DataCamp guru