The best way to count objects in Python is to use the collections.Counter class that was created for this purpose. It acts like a Python recorder, but is a little easier to use when counting. You can simply pass a list of objects and it will automatically calculate them for you.
>>> from collections import Counter >>> c = Counter(['hello', 'hello', 1]) >>> print c Counter({'hello': 2, 1: 1})
Counter also has some useful methods, such as most_common, to learn more.
One of the methods of the Counter class, which can also be very useful, is the update method. After you have created the Counter instance by passing the list of objects, you can do the same with the update method, and it will continue to count without discarding the old counters for the objects:
>>> from collections import Counter >>> c = Counter(['hello', 'hello', 1]) >>> print c Counter({'hello': 2, 1: 1}) >>> c.update(['hello']) >>> print c Counter({'hello': 3, 1: 1})
source share