Python – Combinations of sum with tuples in tuple list

Sometimes, while working with data, we can have a problem in which we need to perform tuple addition among all the tuples in list. This can have application in many domains. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using combinations() + list comprehension
This problem can be solved using combinations of above functions. In this, we use combinations() to generate all possible combination among tuples and list comprehension is used to feed addition logic.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Summation combination in tuple lists
# Using list comprehension + combinations
from itertools import combinations
  
# initialize list 
test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Summation combination in tuple lists
# Using list comprehension + combinations
res = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)] 
  
# printing result
print("The Summation combinations are : " + str(res))

chevron_right


Output :



The original list : [(2, 4), (6, 7), (5, 1), (6, 10)]
The Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)]

 

Method #2 : Using list comprehension + zip() + operator.add + combinations()
The combinations of above methods can also solve this problem. In this, we perform the task of addition using add() and the like indexed elements are linked using zip().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Summation combination in tuple lists
# Using list comprehension + zip() + operator.add + combinations()
from itertools import combinations
import operator
  
# initialize list 
test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Summation combination in tuple lists
# Using list comprehension + zip() + operator.add + combinations()
res = [(operator.add(*a), operator.add(*b))\
    for a, b in (zip(y, x) for x, y in combinations(test_list, 2))]
  
# printing result
print("The Summation combinations are : " + str(res))

chevron_right


Output :

The original list : [(2, 4), (6, 7), (5, 1), (6, 10)]
The Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.