Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of Python Counter

Tags:

python

counter

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).

like image 339
mgold Avatar asked Jul 28 '13 00:07

mgold


People also ask

How do you get the size of a counter in Python?

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.

What is Python counter?

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.

Is counter Python slow?

Counter is slow, it's actually quite fast, but it's a general purpose tool, counting characters is just one of many applications.

What is counter in Python collection?

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.


1 Answers

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.

like image 124
Peter DeGlopper Avatar answered Oct 03 '22 00:10

Peter DeGlopper