How to count unique values inside a list
Last Updated :
19 Apr, 2023
There are several methods for finding or counting unique items inside a list in Python. Here we’ll discuss 3 methods.
Method 1:
The first method is the brute force approach. This method is not very much efficient as it takes more time and space. In this method, we take an empty array and a count variable(set to be zero). 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.
Example:
Python3
input_list = [ 1 , 2 , 2 , 5 , 8 , 4 , 4 , 8 ]
l1 = []
count = 0
for item in input_list:
if item not in l1:
count + = 1
l1.append(item)
print ( "No of unique items are:" , count)
|
Output:
No of unique items are: 5
Time complexity: O(n), where n is the length of the list
Auxiliary Space: O(n), extra space of size n is required
Method 2:
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. We will create a list using the keys, the length of the list will be our answer.
Python3
from collections import Counter
input_list = [ 1 , 2 , 2 , 5 , 8 , 4 , 4 , 8 ]
items = Counter(input_list).keys()
print ( "No of unique items in the list are:" , len (items))
|
Output:
No of unique items in the list are: 5
If we print the length of the dictionary created using Counter will also give us the result. But this method is more understandable.
Method 3:
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.
Python3
input_list = [ 1 , 2 , 2 , 5 , 8 , 4 , 4 , 8 ]
new_set = set (input_list)
print ( "No of unique items in the list are:" , len (new_set))
|
Output:
No of unique items in the list are: 5
Time complexity: O(n), where n is the length of input_list
Auxiliary Space: O(n), extra space required for set.
Method 4:
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.
Python
input_list = [ 1 , 2 , 2 , 5 , 8 , 4 , 4 , 8 ]
new_set = [ x for i, x in enumerate (input_list) if x not in input_list[:i]]
print ( "No of unique items in the list are:" , len (new_set))
|
Output:
No of unique items in the list are: 5
Please Login to comment...