Search code examples
pythonlistcounter

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


I have a list which has repeating items and I want a list of the unique items with their frequency.

For example, I have ['a', 'a', 'b', 'b', 'b'], and I want [('a', 2), ('b', 3)].

Looking for a simple way to do this without looping twice.


Solution

  • 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)]