ID : 323
viewed : 59
Tags : PythonPython List
91
This article will introduce different methods to count unique values inside list. using the following methods:
collections.Counter
set(listName)
np.unique(listName)
collections.counter
to Count Unique Values in Python Listcollections
is a Python standard library, and it contains the Counter
class to count the hashable objects.
Counter
class has two methods :
keys()
returns the unique values in the list.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.
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
set
to Count Unique Values in Python Listset
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.
words = ['Z', 'V', 'A', 'Z','V'] print(len(set(words)))
Output:
3
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
.
import numpy as np words = ['Z', 'V', 'A', 'Z','V'] np.unique(words) print(len(np.unique(words)))
Output:
3