Size of Python Counter

Question:

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

Asked By: mgold

||

Answers:

You can look through the source code; there is no cached value recording the number of items in the Counter. So the best you can do is sum(c.itervalues()).

In [108]: import collections

In [109]: c = collections.Counter(x=3, y=7)

In [110]: sum(c.itervalues())
Out[110]: 10
Answered By: unutbu

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.

Answered By: Peter DeGlopper

In python 3.10, c.total() can be simply used to obtain the result.

import collections
c = collections.Counter(x=3, y=7)
c.total()

# result: 10
Answered By: holyeeee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.