How to Count Unique Values in Python List

  1. Use collections.counter to Count Unique Values in Python List
  2. Use set to Count Unique Values in Python List
  3. Use numpy.unique to Count the Unique Values in Python List

This article will introduce different methods to count unique values inside list. using the following methods:

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

Use collections.counter to Count Unique Values in Python List

collections is a Python standard library, and it contains the Counter class to count the hashable objects.

Counter class has two methods :

  1. keys() returns the unique values in the list.
  2. values() returns the count of every unique value in the list.

We can use the len() function to get the number of unique values by passing the Counter class as the argument.

Example Codes:

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 unqiue values in the list, after we convert the list to a set using set() function.

Example Codes:

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

Output :

3

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

numpy.unique returns the unique values of the input array-like data, and also returns the count of each unique value if the return_counts parameter is set to be True.

Example Codes:

import numpy as np

words = ['Z', 'V', 'A', 'Z','V']

np.unique(words)

print(len(np.unique(words)))

Output:

3

Related Article - Python List

  • How to List the Alphabet in Python
  • How to Convert a List to String in Python
  • comments powered by Disqus