Keeping tallies in Python

Python's collections module has some of the most consistently useful collection data structures you will need for everyday programming. Here's one I didn't know about:

collections.Counter (Python 2.7 only!)

It is designed to keep "tallies" or count instances of something. The example will make it all clear:


from collections import Counter
cars = Counter()
# I see one go past, it is red
cars['red'] += 1
# And a green one
cars['blue'] += 1
# etc


This is pretty much like a defaultdict with an integer value, but it is convenient and neat, with some useful constructors. Don't you think?

Popular posts from this blog

PyGTK, Py2exe, and Inno setup for single-file Windows installers

ESP-IDF for Arduino Users, Tutorials Part 2: Delay

How to install IronPython2 with Mono on Ubuntu