6 Ways in Python to Count Unique Values in List

Introduction

In Python, we have duplicate elements present in the list. Sometimes, we occur in a situation where we need to count unique values in the list in Python. So we will be discussing the various ways to find the unique values in an array or list. And also, print the number of unique elements present in the list.

Python Unique element in the list

Unique elements are the elements which appears only one time in a list.

Suppose, we have a list = [1, 2, 3, 2, 3, 5, 1, 6, 1]. Here we see that 1 comes 3 times, 2 comes 2 times, 3 comes 2 times, 5 and 6 comes single time. If we count the unique elements in the list, it will be only 5 as [1, 2, 3, 5, 6].

Different Methods to Count Unique Values

Let us understand the all the different methods through which we can calculate the count of unique elements in the list or an array with the help of examples:

1. Python Count Unique Values in List by normal Brute Force method

We call this method a brute force approach. This method is not that efficient method as it more time and more space. This approach will take an empty list and a count variable, which will be set to 0. we will traverse from the start till the end and check if the value is not present in the empty list. Then, we will append it and increase the count variable by 1. If it is not present in the empty list, then we will not count it, not append it in the empty list.

# take an input list as lst 
lst = [1, 2, 3, 5, 1, 2, 6, 7] 
print("Input list : ",lst)

#Empty list 
lst1 = [] 

count = 0

# traverse the array 
for i in lst: 
	if i not in lst1: 
		count = count + 1
		lst1.append(i) 

# printing the output 
print("Output list : ",lst1)
print("No. of unique items are:", count) 

Output:

Input list :  [1, 2, 3, 5, 1, 2, 6, 7]
Output list :  [1, 2, 3, 5, 6, 7]
No. of unique items are: 6

Explanation:

Here firstly, we have taken an input list and printed the input list. Secondly, we have taken an empty list and a count variable which is set to 0. Thirdly, we have traversed the list from the start and checked if the value is not present in the empty list or not. If the value is not present in the empty list, we increase the count value by 1 and append that value in the empty list. If we find that the elements are present in the list, we do not append it in the empty list, and neither increases the count value by 1. Finally, we have printed the empty list that contains unique values now and the count of the list. Hence, we can see all the unique elements in the list.

2. By using counter

In this method, we will be using a counter function from the collections library. In this, we will be creating a dictionary with the help of the counter() function. The keys will be the unique elements, and the values will be the number of that unique element. By taking the keys from the dictionary, we will be creating a list and print the length of the list.

#import Counter from collections
from collections import Counter

#input of list
lst = [1, 2, 3, 1, 2, 5, 3, 4, 3, 6]
print("Input list : ",lst)

lst1 = Counter(lst).keys() 
print("output list : ",lst1)
print("No of unique elements in the list are:", len(lst1)) 

Output:

Input list :  [1, 2, 3, 1, 2, 5, 3, 4, 3, 6]
output list :  dict_keys([1, 2, 3, 5, 4, 6])
No of unique elements in the list are: 6

Explanation:

Here firstly, we have imported the Counter() function from the collections library. Secondly, we have taken the input list and printed the input list. Thirdly, we have applied the counter(), an unordered collection where the elements are stored as dictionary keys, and their counts are stored as dictionary values. From the input list, we have created a new list in which only the elements whose key values are present once are stored. These all elements are distinct in the list. Finally, we have printed the empty list that contains unique values now and the count of the list. Hence, we can see all the unique elements in the list.

3. Python Count Unique Values In List By using the set

In this method, we will use the built-in data type of python called Set. We will take the input in the form of a list then convert it into a set. As we all know set doesn’t contain any duplicate elements in it. It will contain only the unique elements in it, and we will print the length of the list using the length() function.

# Take input list
lst = [2, 3, 5, 2, 4, 3, 1, 5, 2, 1]
print("Input list : ", lst)

lst1 = set(lst)
print("Output list : ",lst1)
print("No of unique elements in the list are:", len(lst1))

Output:

Input list :  [2, 3, 5, 2, 4, 3, 1, 5, 2, 1]
Output list :  {1, 2, 3, 4, 5}
No of unique elements in the list are: 5

Explanation:

Here firstly, we have taken an input list and printed the input list. Secondly, we have converted the input list into a set. Set, which is the built-in data type in python, contains only the unique elements in it. Thirdly, we have stored all the values in another list. Finally, we have printed the empty list that contains unique values now and the count of the list. Hence, we can see all the unique elements in the list.

4. By using numpy.unique

In this method, we will import the numpy library with its alias name as np. In the numpy library, we will use numpy.unique() function, which returns the unique value of the input list. We can also return the count of each unique value if the return count parameter is set to be True.

#import numpy module
import numpy as np

#input list
lst = [1,2,3,4,2,5,1,2,6,3]
print("Input list : ",lst)

lst1 = np.unique(lst)
print("Output list : ", lst1)
print("No of unique elements in the list are:", len(lst1))

Output:

Input list :  [1, 2, 3, 4, 2, 5, 1, 2, 6, 3]
Output list :  [1 2 3 4 5 6]
No of unique elements in the list are: 6

Explanation:

Here firstly, we have imported the numpy module as an alias np. Secondly, we have taken the input list and printed the input list. Thirdly, we have applied the numpy. unique() which will keep only the unique values of the list and stored in another list. Finally, we have printed the empty list that contains unique values now and the count of the list. Hence, we can see all the unique elements in the list.

5. Python Count Unique Values In List Using pandas dict + zip function

In this method, we will be using a dictionary with a combination of zip functions to find the string’s unique values by converting them into a list.

#input as a string

str="latracalsolutions"
unique = dict(zip(list(str),[list(str).count(i) for i in list(str)]))
print("Dictionary : ",unique)
print("count : ",len(unique))

Output:

Dictionary :  {'l': 3, 'a': 3, 't': 2, 'r': 1, 'c': 1, 's': 2, 'o': 2, 'u': 1, 'i': 1, 'n': 1}
count :  10

Explanation:

Here firstly, we have taken a string as str = latracalsolutions. Secondly, we have applied the dict function inside that we have applied the zip function, and inside it, we have converted a string into a list and counted the keys and values by traversing the list. Thirdly, we have taken a variable unique in which we have stored the dictionary’s keys and values. Finally, we have printed the length of the dictionary with the help of the length function in python.

6. Using pandas dataframe.

In this method, we will import pandas as an alias name pd. we will take input in pandas’ data frame.

import pandas as pd 

df = pd.DataFrame({ 
'Marks' : [65, 65, 64, 
			58, 67, 60, 
			58, 65]}, 
	

Names = ['sid', 'sam', 'Nia', 
			'Jenny', 'virat', 'Lucifer', 
			'Ramu', 'Nikita']) 
 
n = len(pd.unique(df['Marks'])) 

print("No.of.unique values :",n)

Output:

No.of.unique values : 5

Explanation:

Here firstly, we have imported the pandas’ module with an alias name as pd. Secondly, we have created a data frame with the input of marks and names. Thirdly, we have created a variable n in which we will store the value. We have applied the unique function in marks in pandas and then calculated its length with the length function and stored it in variable n. At last, we have printed the output.

Also, Read

Conclusion

In this tutorial, we have seen what the unique elements in the list are. Also, we have seen different methods through which we can find the unique elements in the list. We have also counted the unique elements in the list and printed the count. All the methods are explained in detail with the help of examples. All the examples are also explained, which will give you a better understanding of the methods. You can use any of the programs to find the count of unique elements in the list according to your need and choice.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments