Counter.total

len(c) is the number of DISTINCT elements; c.total() is the number of elements counted. It is a plain sum, so negative counts pull it down.

Counter methodPython 3.10+Live demo
Common call
Counter('hello').total()
Returns
5 — while len() is 4
Replaces
sum(c.values())
Watch out
negative counts are summed too; +c drops them first
Counter.total()
→ int

Demo

Live evaluation
Total counts every letter; len counts distinct letters.
Try:
Inputs
textstrany text
Code
from collections import Counter
c = Counter('hello')
(c.total(), len(c))
Result
(5, 4)

For "aab" minus "bbbc" the counts become a: 2, b: -2, c: -1, so total() is -1 while (+c).total() — only the positive counts — is 2.

Common patterns

Percentages
Divide each count by the total.
from collections import Counter
c = Counter(answers)
shares = {k: n / c.total() for k, n in c.items()}
Ignore negative counts
Unary + keeps only positive counts.
from collections import Counter
in_stock = (+inventory).total()

Examples

1. Total vs distinct
from collections import Counter c = Counter('hello') (c.total(), len(c))
Returns
(5, 4)
2. Same as sum(values())
from collections import Counter Counter(a=10, b=5, c=0).total()
Returns
15
3. Negative counts reduce it
from collections import Counter Counter(a=3, b=-5).total()
Returns
-2
4. Empty counter
from collections import Counter Counter().total()
Returns
0
5. Float counts give a float
from collections import Counter Counter(a=0.5, b=2).total()
Returns
2.5

Pitfalls

1. Using len() for the number of items
len() counts keys, not occurrences.
len(c)
from collections import Counter
len(Counter(['x', 'x', 'x']))
1
c.total()
from collections import Counter
Counter(['x', 'x', 'x']).total()
3
2. Counting shortages as stock
After subtract(), total() nets negatives against positives.
c.total()
from collections import Counter
c = Counter(apples=5)
c.subtract(pears=2)
c.total()
3
(+c).total()
from collections import Counter
c = Counter(apples=5)
c.subtract(pears=2)
(+c).total()
5

When to use

Use it
  • Number of counted items (sample size)
  • Normalising counts to proportions
Reach for something else
  • Python before 3.10 → sum(c.values())
  • Number of distinct elements → len(c)

Notes

CPython impl
return sum(self.values()) — in Lib/collections/__init__.py
Versions
Added in Python 3.10 (docs.python.org)

FAQ

counter.total() on Python 3.10+, or sum(counter.values()) on any version. len(counter) is the number of distinct elements.