Python | Extract unique tuples from list, Order Irrespective

Sometimes, while working with data, we can have a problem in which we need to check for similar records and eradicate them. When elements are ordered, this case has been discussed before. But sometimes, we might have to ignore the order and has to be removed in case similar elements occur. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + set()
The combination of above functionalities can be clubbed to perform this particular task. In this, we check for each pair and add to a set for reference to check if it has existed before and add if it’s a new one.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Extract unique tuples from list(Order Irrespective)
# using list comprehension + set()
  
# initialize tuples list 
test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract unique tuples from list(Order Irrespective)
# using list comprehension + set()
res = set() 
temp = [res.add((a, b)) for (a, b) in test_list 
              if (a, b) and (b, a) not in res]
  
# printing result
print("The list after duplicated removal : " + str(list(res)))

chevron_right


Output :

The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]
The list after duplicated removal : [(4, 5), (1, 3), (1, 10)]

 

Method #2 : Using frozenset()
Another method to perform this particular task is to use frozenset(). This function eliminates internally the similar elements irrespective of order.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Extract unique tuples from list(Order Irrespective)
# using frozenset()
  
# initialize tuples list 
test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract unique tuples from list(Order Irrespective)
# using frozenset()
res = set(tuple(frozenset(sub)) for sub in set(test_list))
  
# printing result
print("The list after duplicated removal : " + str(list(res)))

chevron_right


Output :

The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]
The list after duplicated removal : [(4, 5), (1, 3), (1, 10)]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.