Write a Python program to Extract Symmetric Tuples


The program is written in Python and it finds the symmetric tuples in a list of tuples. Initially, a list val is created containing 6 tuples. The program uses set operations and set comprehensions to find the symmetric tuples. A set comprehension is used to create a set temp from the original list val. This set comprehension contains the tuples from val in reverse order, i.e., (b, a) instead of (a, b).

The program then uses the set intersection operator & to find the tuples in val that are also present in temp. These are the symmetric tuples. Finally, another set comprehension is used to create a set res from the symmetric tuples in temp, but only if the first element of each tuple is less than the second element. The program prints the original list val and the set of symmetric tuples res.

Source Code

val = [(18, 23), (2, 9), (7, 6), (9, 2), (10, 2), (23, 18)]
print("The original list is : " ,val)
temp = set(val) & {(b, a) for a, b in val}
res = {(a, b) for a, b in temp if a < b}
 
print("The Symmetric tuples : " , res)

Output

The original list is :  [(18, 23), (2, 9), (7, 6), (9, 2), (10, 2), (23, 18)]
The Symmetric tuples :  {(2, 9), (18, 23)}


Example Programs