How to count unique values inside a list
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
# taking an input listinput_list = [1, 2, 2, 5, 8, 4, 4, 8] # taking an input listl1 = [] # taking an countercount = 0 # travesing the arrayfor item in input_list: if item not in l1: count += 1 l1.append(item) # printing the outputprint("No of unique items are:", count) |
Output:
No of unique items are: 5
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
# importing Counter modulefrom collections import Counter input_list = [1, 2, 2, 5, 8, 4, 4, 8] # creating a list with the keysitems = 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] # converting our list to setnew_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


