![]() |
VOOZH | about |
There are several methods for finding or counting unique items inside a list in Python. Here we'll discuss 3 methods.
The first method is the brute force approach.We traverse from the start and check the items. If the item is not in the empty list(as it has taken empty) then we will add it to the empty list and increase the counter by 1. While traveling if the item is in the taken list(empty list) we will not count it.
Output:
No of unique items are: 5Time complexity: O(n^2), where n is the length of the list
Auxiliary Space: O(n), extra space of size n is required
In this method, we will use a function name Counter. The module collections have this function. Using the Counter function we will create a dictionary. The keys of the dictionary will be the unique items and the values will be the number of that key present in the list.
Output:
No of unique items in the list are: 5If we print the length of the dictionary created using Counter will also give us the result. But this method is more understandable.
In this method, we will convert our list to set. As sets don't contain any duplicate items then printing the length of the set will give us the total number of unique items.
Output:
No of unique items in the list are: 5Time complexity: O(n), where n is the length of input_list
Auxiliary Space: O(n), extra space required for set.
In this method, we will remove all the duplicate from our list. As list don't contain any duplicate items then printing the length of the list will give us the total number of unique items.
Output:
No of unique items in the list are: 5