Use collections.counter
:
from collections import Counter
L = ["brown", "brown", "brown", "red", "red", "yellow", "yellow"]
cnt = Counter(L)
print cnt
print cnt.keys(), cnt.values()
Output:
Counter({'brown': 3, 'yellow': 2, 'red': 2})
['brown', 'yellow', 'red'] [3, 2, 2]
The resulting counter object can be manipulated as a dictionary, with additional convenient routines such as cnt.most_common(n)
which will return the n
most common elements and their counts.