Skip to content

Commit 8c598db

Browse files
authored
bpo-25478: Add total() method to collections.Counter (pythonGH-25829)
1 parent d52bbde commit 8c598db

File tree

4 files changed

+21
-1
lines changed

4 files changed

+21
-1
lines changed

Doc/library/collections.rst

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,16 @@ For example::
313313

314314
.. versionadded:: 3.2
315315

316+
.. method:: total()
317+
318+
Compute the sum of the counts.
319+
320+
>>> c = Counter(a=10, b=5, c=0)
321+
>>> c.total()
322+
15
323+
324+
.. versionadded:: 3.10
325+
316326
The usual dictionary methods are available for :class:`Counter` objects
317327
except for two which work differently for counters.
318328

@@ -342,7 +352,7 @@ All of those tests treat missing elements as having zero counts so that
342352

343353
Common patterns for working with :class:`Counter` objects::
344354

345-
sum(c.values()) # total of all counts
355+
c.total() # total of all counts
346356
c.clear() # reset all counts
347357
list(c) # list unique elements
348358
set(c) # convert to a set

Lib/collections/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -581,6 +581,10 @@ def __missing__(self, key):
581581
# Needed so that self[missing_item] does not raise KeyError
582582
return 0
583583

584+
def total(self):
585+
'Sum of the counts'
586+
return sum(self.values())
587+
584588
def most_common(self, n=None):
585589
'''List the n most common elements and their counts from the most
586590
common to the least. If n is None, then list all element counts.

Lib/test/test_collections.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2066,6 +2066,10 @@ def test_init(self):
20662066
self.assertRaises(TypeError, Counter, (), ())
20672067
self.assertRaises(TypeError, Counter.__init__)
20682068

2069+
def test_total(self):
2070+
c = Counter(a=10, b=5, c=0)
2071+
self.assertEqual(c.total(), 15)
2072+
20692073
def test_order_preservation(self):
20702074
# Input order dictates items() order
20712075
self.assertEqual(list(Counter('abracadabra').items()),
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Added a *total()* method to collections.Counter() to compute the sum of the
2+
counts.

0 commit comments

Comments
 (0)