Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Get unique tuples from list

  • Last Updated : 27 Aug, 2019

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()




# 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))
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().




# 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))
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
Recommended Articles
Page :

Start Your Coding Journey Now!