Python - How To Count Unique Values in Python List

ID : 323

viewed : 59

Tags : PythonPython List

vote vote

91

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

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 HOW TO?