# 8 Ways in Python to Count Unique Values in List

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.

Unique Values in List are the collection of distinctive values which are not the same. Many times, we require to fetch the nonrepititve values from a list. To do so, you can use loops, sets, counter module,s and many other ways. In this post, we’ll go through every possible way to get unique values from the list.

Contents

## 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].

## Why do we need to get the unique elements from the list?

In many scenarios, the data is collected in such a way that it appends repetitive user requests. For example in IP logger applications, every time a user connects to the logger, its IP is appended to the database. Now, considering this, if you want to extract the list of IPs connected to the logger, you only need unique values.

## 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
2. By using Counter
3. Python Count Unique Values In List By using the Set
4. By using numpy.unique
5. Python Count Unique Values In List Using pandas dict + zip function
6. Using Pandas Dataframe
7. Dict Comprehension to get Unique Values
8. Using List Comprehension

## 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.

## 7. Dict Comprehension to get Unique Values

Dictionary comprehension is an easy way to avoiding repetitive elements from the list. Since the elements in the dictionary are unique, you can avoid appending repetitive elements to it. The following example will help you to understand this better –

```lst = ["p","y","p","i","y"]
my_dict = {i:lst.count(i) for i in lst}
print("Unique items: ", my_dict.keys(),"  ", len(my_dict))
```

Output

``Unique items:  dict_keys(['p', 'y', 'i'])    3``

Explanation

We first begin with our default list which has repetitive elements. Then we declare a dictionary comprehension with list element as a key and list count as a value. Then print out the dictionary keys to get the unique values.

## 8. Using List Comprehension

List comprehension is an easy way of declaring elements in the list without using a loop. You can even initialize dictionaries with unique counts of elements. In this specific example, we’ll use dict() + zip() function to create a counter for unique elements.

```lst = ["p","y","p","i","y"]
unique = dict(zip(lst,[lst.count(i) for i in lst]))
print(unique)
print("Unique items: ", len(unique))
```

Output

``````{'p': 2, 'y': 2, 'i': 1}
Unique items:  3``````

Explanation

We first declare the list with repetitive elements inside it. Then we declare a dictionary function that takes the zip() function to combine the list and its count. Counts are determined by the lst.count() function inside the list comprehension.

Zip function makes sure that the dict function iterates simultaneously through the list member and its count. After printing the dictionary you can verify that it contains the count of each unique element. Moreover, you can use the len() function over the dictionary to check a number of unique values.

## How To Count The Frequency Of Unique Values In The List?

Counting frequency can be done in many ways, namely by using loops, by using count() fucntion, and other ways. In this example, we’ll use the count() function to capture the freuqnecy of unique items in the list.

Code

```lst = ["p","y","p","i","y"]
unique = list(set(lst))
frequency = {}
for item in unique:
frequency[item] = lst.count(item)
print("Frequency of items: ", frequency)
```

Output

``Frequency of items:  {'y': 2, 'i': 1, 'p': 2}``

Explanation

We first declare a list with repetitive elements. Then we extract the unique elements by using the set() function. As we know the unique elements we can loop through them to extract the counts of them in the original list. In this case, we’ll use the dictionary to save the counter.

## How to count unique values in a List of Dictionary?

Code:

```lst=[{"a":1}, {"b":2}, {"a":1}]
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 :  [{'a': 1}, {'b': 2}, {'a': 1}]
Output list :  [{'a': 1}, {'b': 2}]
No. of unique items are: 2`````` 