Python has a "batteries included" philosophy that means a lot of useful things are included in their standard library. By no means have I plumbed the depth of what's included. I still run across things that are extremely useful and fit exactly what I need.

Today I encountered the 'Counter' object which is part of the collections library.

The situation was that I had a list of items and I needed to get counts of each item. Here is an example to illustrate.

>>> from collections import Counter
>>> alpha = ['a', 'c', 'b', 'c', 'c', 'b', 'a', 'd', 'b', 'c']
>>> Counter(alpha)
Counter({<'c': 4, <'b': 3, <'a': 2, <'d': 1})

# I need the 2 items with the largest count.
>>> Counter(alpha).most_common(2)
[(<'c', 4), (<'b', 3)]

This returns a list of tuples containing the item and the count. Perfect!

There are additional methods and useful ways to deal with Counter objects, so be sure to check out the documentation.

Bonus Reminder To Self:

  • [] refers to a list
  • () refers to a tuple
  • {} refers to a dictionary