I want to know how many items are in a Python Counter, including the duplicates. I tried len
and it tells me the number of unique items:
>>> c = Counter(x=3,y=7)
>>> len(c)
2
The best I have is sum(c.itervalues())
which I suppose isn't terrible, but I was hoping the Counter object caches the value so I could access it in O(1).
In Python, you can count the total number of elements in a list or tuple with the built-in function len() and the number of occurrences of an element with the count() method.
Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.
Counter is slow, it's actually quite fast, but it's a general purpose tool, counting characters is just one of many applications.
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.
The Counter docs give your sum(c.itervalues())
answer as the standard pattern for this in the "Common patterns for working with Counter objects" section, so I doubt there's anything better.
As with the other iter*
methods on dictionaries, in Python 3 itervalues
is replaced by values
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With