How to get unique values with respective occurrence count from a list in Python?

With Python 2.7+, you can use collections.Counter.

Otherwise, see this counter receipe.

Under Python 2.7+:

from collections import Counter
input =  ['a', 'a', 'b', 'b', 'b']
c = Counter( input )

print( c.items() )

Output is:

[(‘a’, 2), (‘b’, 3)]

Leave a Comment