Sum of all counts in a collections.Counter

PythonPython 3.xCounter

Python Problem Overview


What is the best way of establishing the sum of all counts in a collections.Counter object?

I've tried:

sum(Counter([1,2,3,4,5,1,2,1,6]))

but this gives 21 instead of 9?

Python Solutions


Solution 1 - Python

The code you have adds up the keys (i.e. the unique values in the list: 1+2+3+4+5+6=21).

To add up the counts, use:

In [4]: sum(Counter([1,2,3,4,5,1,2,1,6]).values())
Out[4]: 9

This idiom is mentioned in the documentation, under "Common patterns".

Solution 2 - Python

Sum the values:

sum(some_counter.values())

Demo:

>>> from collections import Counter
>>> c = Counter([1,2,3,4,5,1,2,1,6])
>>> sum(c.values())
9

Solution 3 - Python

Starting in Python 3.10, Counter is given a total() function which provides the sum of the counts:

from collections import Counter

Counter([1,2,3,4,5,1,2,1,6]).total()
# 9

Solution 4 - Python

sum(Counter([1,2,3,4,5,1,2,1,6]).values())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBazView Question on Stackoverflow
Solution 1 - PythonNPEView Answer on Stackoverflow
Solution 2 - PythonMartijn PietersView Answer on Stackoverflow
Solution 3 - PythonXavier GuihotView Answer on Stackoverflow
Solution 4 - PythonmartynView Answer on Stackoverflow