Skip to content

bpo-25478: Add total() method to collections.Counter #25829

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Doc/library/collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,16 @@ For example::

.. versionadded:: 3.2

.. method:: total()

Compute the sum of the counts.

>>> c = Counter(a=10, b=5, c=0)
>>> c.total()
15

.. versionadded:: 3.10

The usual dictionary methods are available for :class:`Counter` objects
except for two which work differently for counters.

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

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

sum(c.values()) # total of all counts
c.total() # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
Expand Down
4 changes: 4 additions & 0 deletions Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,10 @@ def __missing__(self, key):
# Needed so that self[missing_item] does not raise KeyError
return 0

def total(self):
'Sum of the counts'
return sum(self.values())

def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -2060,6 +2060,10 @@ def test_init(self):
self.assertRaises(TypeError, Counter, (), ())
self.assertRaises(TypeError, Counter.__init__)

def test_total(self):
c = Counter(a=10, b=5, c=0)
self.assertEqual(c.total(), 15)

def test_order_preservation(self):
# Input order dictates items() order
self.assertEqual(list(Counter('abracadabra').items()),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added a *total()* method to collections.Counter() to compute the sum of the
counts.