.. 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.
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
# 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.
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()),
--- /dev/null
+Added a *total()* method to collections.Counter() to compute the sum of the
+counts.