Python | Get unique tuples from list

Sometimes, while working with Python list, we can come across a problem in which we require to find the unique occurrences of list. Having elementary data types is easy to handle, but sometime, we might have complex data types and the problem becomes new in that cases. Let’s discuss certain ways in which tuples are handled for this problem.

Method #1 : Using list() + set()
Alike integers, being immutable these can also be handled by set() for removal of the duplicates. It converts the list to set and removes duplicates and converted back to list by list()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get unique tuples from list
# using set() + list()
  
# initializing list
test_list = [(4, 5), (6, 1), (4, 5), (6, 1)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Get unique tuples from list
# using set() + list()
res = list(set(test_list))
  
# printing result 
print("List after removal of duplicates " + str(res))

chevron_right


Output :



The original list is : [(4, 5), (6, 1), (4, 5), (6, 1)]
List after removal of duplicates [(4, 5), (6, 1)]

 

Method #2 : Using dict.fromkeys() + list()
Since newer versions of Python dictionaries, remember their order of insertion, the list contents can be converted to dictionary element list, which remembers the order and removes the duplicates. It is converted back using list().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get unique tuples from list
# using dict.fromkeys() + list()
  
# initializing list
test_list = [(4, 5), (6, 1), (4, 5), (6, 1)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Get unique tuples from list
# using dict.fromkeys() + list()
res = list(dict.fromkeys(test_list))
  
# printing result 
print("List after removal of duplicates " + str(res))

chevron_right


Output :

The original list is : [(4, 5), (6, 1), (4, 5), (6, 1)]
List after removal of duplicates [(4, 5), (6, 1)]


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.