![]() |
VOOZH | about |
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()
Time Complexity: O(n)
Space Complexity: O(n)
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().
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:
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.