How to Count Unique Values in Python List

Jinku Hu Feb 02, 2024
  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
How to Count 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 unique values in the list after we convert the list to a set using the 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
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - Python List