How do I count unique values inside a list How do I count unique values inside a list python python

How do I count unique values inside a list


In addition, use collections.Counter to refactor your code:

from collections import Counterwords = ['a', 'b', 'c', 'a']Counter(words).keys() # equals to list(set(words))Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b'][2, 1, 1]


You can use a set to remove duplicates, and then the len function to count the elements in the set:

len(set(new_words))


values, counts = np.unique(words, return_counts=True)

More Detail

import numpy as npwords = ['b', 'a', 'a', 'c', 'c', 'c']values, counts = np.unique(words, return_counts=True)

The function numpy.unique returns sorted unique elements of the input list together with their counts:

['a', 'b', 'c'][2, 1, 3]