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

counter, list, python

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

Problem

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.

Original source

Related problems