Combinations of sum with tuples in tuple list in Python


If it is required to get the combinations of sum with respect to tuples in a list of tuples, the 'combinations' method and the list comprehension can be used.

The 'combinations' method returns 'r' length subsequence of elements from the iterable that is passed as input. The combinations are shown in lexicographic sort order. The combination tuples are displayed in a sorted order.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

Below is a demonstration of the same −

Example

Live Demo

from itertools import combinations
my_list = [( 67, 45), (34, 56), (99, 123), (10, 56)]

print ("The list of tuple is : " )
print(my_list)

my_result = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(my_list, 2)]

print("The summation combination result is : ")
print(my_result)

Output

The list of tuple is :
[(67, 45), (34, 56), (99, 123), (10, 56)]
The summation combination result is :
[(101, 101), (166, 168), (77, 101), (133, 179), (44, 112), (109, 179)]

Explanation

  • A list of tuples is defined, and is displayed on the console.
  • The combinations method is used to return subsequence of length 2, as mentioned in the method.
  • The list of tuple is iterated, and the elements from every tuple in the list of tuple is added to the element from the next tuple.
  • This value is assigned a variable.
  • This variable is the output that is displayed on the console.

Updated on: 11-Mar-2021

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements