69

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?

Rarblack
  • 4,559
  • 4
  • 22
  • 33
Baz
  • 12,713
  • 38
  • 145
  • 268

4 Answers4

87

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".

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • ...btw, this is always going to be equal to len([1,2,3,4,5,1,2,1,6]), so it use that method only when you just have the counter... – ntg Mar 21 '22 at 10:35
26

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
25

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
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
3
sum(Counter([1,2,3,4,5,1,2,1,6]).values())
martyn
  • 676
  • 7
  • 17