Skip to content
Related Articles

Related Articles

Python – Combinations of sum with tuples in tuple list

Improve Article
Save Article
Like Article
  • Last Updated : 17 Dec, 2019

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.




# 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))
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().




# 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))
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
Recommended Articles
Page :

Start Your Coding Journey Now!