How do I count unique values inside a list
Solution 1:
In addition, use collections.Counter to refactor your code:
from collections import Counter
words = ['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]
Solution 2:
You can use a set to remove duplicates, and then the len function to count the elements in the set:
len(set(new_words))
Solution 3:
values, counts = np.unique(words, return_counts=True)
More Detail
import numpy as np
words = ['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]