Write a Python program to Tuple List intersection (Order irrespective)


The program is written in Python and performs the following operations:

  • Defines two lists of tuples called "val1" and "val2".
  • Prints the two lists of tuples.
  • Defines a new set "res" by taking the intersection of two sets, each created from the corresponding list of tuples.
  • The sets are created by first sorting each tuple in ascending order and then converting the sorted tuple to a list.
  • The sorted list is then converted back to a tuple, and finally, added to the set.
  • Prints the resulting set after the intersection.

The final output of the program will be the common tuples (if any) between the two lists "val1" and "val2". The intersection of the sets will return the common tuples, if any, in the two lists, after sorting each tuple in ascending order.

Source Code

val1 = [(3, 4), (5, 6), (9, 10), (4, 5)]
val2 = [(5, 4), (3, 4), (6, 5), (9, 11)]
print("List 1 : ",val1)
print("List 2 : ",val2)
 
res = set([tuple(sorted(ele)) for ele in val1]) & set([tuple(sorted(ele)) for ele in val2])
 
print("List after intersection : ",res)

Output

List 1 :  [(3, 4), (5, 6), (9, 10), (4, 5)]
List 2 :  [(5, 4), (3, 4), (6, 5), (9, 11)]

List after intersection :  {(4, 5), (5, 6), (3, 4)}

Example Programs