# Python Count Unique Values in List

0
820

## Python Count Unique Values in List

This article will cover various methods for counting unique values inside a list. using the methods listed below:

• collections.Counter
• set(listName)
• np.unique(listName)

## Use collections.counter to Count Unique Values in Python List

The Counter class is a part of the Python standard library, and it counts hashable objects.

There are two methods in the Counter class:

1. keys() returns the list’s unique values.

2. The count of each unique value in the list is returned by values().

By passing the Counter class as an argument to the len() function, we can get the number of unique values.

Example

from collections import Counter
words = [‘Z’, ‘V’, ‘A’, ‘Z’,’V’]
print(Counter(words).keys())
print(Counter(words).values())
print(Counter(words))

Output:

[‘V’, ‘A’, ‘Z’]
[2, 1, 2]
3

## Use set to Count Unique Values in Python List

set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. We can get the length of the set to count unique values in the list after we convert the list to a set using the set() function.

Example

words = [‘Z’, ‘V’, ‘A’, ‘Z’,’V’]
print(len(set(words)))

Output

`3`

## Use numpy.unique to Count the Unique Values in Python List

If the return counts parameter is set to True, numpy.unique returns the unique values of the input array-like data, as well as the count of and unique value.

import numpy as np
words = [‘Z’, ‘V’, ‘A’, ‘Z’,’V’]
np.unique(words)
print(len(np.unique(words)))

Output

`3`

Resources:

Count Distinct Problem