Sum all values of a counter in Python 2

Since your question is about Python 2.7, you should use something like this

sum(my_counter.itervalues())

which on Python 3.x is effectively equivalent to

sum(my_counter.values())

In both cases you evaluate the sum lazily and avoid expensive intermediate data structures. Beware of using the Python 3.x variant on Py 2.x, because in the latter case my_counter.values() calculates an entire list of counts and stores it in memory before calculating the sum.


>>> from collections import Counter
>>> sum(Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1}).values())
7

Common patterns for working with Counter objects: sum(c.values())
# total of all counts

Source: https://docs.python.org/2/library/collections.html