Python | Get unique tuples from list
Last Updated :
01 May, 2023
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
test_list = [( 4 , 5 ), ( 6 , 1 ), ( 4 , 5 ), ( 6 , 1 )]
print ("The original list is : " + str (test_list))
res = list ( set (test_list))
print (" List after removal of duplicates " + str (res))
|
Time Complexity: O(n)
Space Complexity: O(n)
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
test_list = [( 4 , 5 ), ( 6 , 1 ), ( 4 , 5 ), ( 6 , 1 )]
print ("The original list is : " + str (test_list))
res = list ( dict .fromkeys(test_list))
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)]
Time Complexity: O(n)
Space Complexity: O(n)
Method #3 Use a loop
Step-by-step approach:
- Initialize the input list and a new empty list.
- Loop through each tuple in the input list.
- Check if the tuple is already in the new list.
- If not, append the tuple to the new list.
- Print the original list and the list without duplicates.
Python3
test_list = [( 4 , 5 ), ( 6 , 1 ), ( 4 , 5 ), ( 6 , 1 )]
print ( "The original list is : " + str (test_list))
res = []
for tup in test_list:
if tup not in res:
res.append(tup)
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)]
Time complexity: O(n^2), because it loops through each tuple in the input list and then loops through the new list to check if the tuple is already present.
Auxiliary space: O(n), because it creates a new list to store the unique tuples.
Share your thoughts in the comments
Please Login to comment...