
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements