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

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 Counterinput =  ['a', 'a', 'b', 'b', 'b']c = Counter( input )print( c.items() )

Output is:

[('a', 2), ('b', 3)]


If your items are grouped (i.e. similar items come together in a bunch), the most efficient method to use is itertools.groupby:

>>> [(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])][('a', 2), ('b', 3)]


>>> mylist=['a', 'a', 'b', 'b', 'b']>>> [ (i,mylist.count(i)) for i in set(mylist) ][('a', 2), ('b', 3)]