5

Python 2.7/3.1 introduced the awesome collections.Counter.

My question: How do I count how many "element appearances" a counter has?

I want this:

len(list(counter.elements()))

But shorter.

sophros
  • 14,672
  • 11
  • 46
  • 75
Ram Rachum
  • 84,019
  • 84
  • 236
  • 374
  • I raised the subject on Python-ideas and Raymond Hettinger said a `Counter.elements_count()` method might be added. Python issue: http://bugs.python.org/issue11733 – Ram Rachum Mar 31 '11 at 22:16
  • This idea was rejected but the issue raised looks slightly different from what the OT is asking about. – sophros Jul 26 '19 at 16:15

1 Answers1

4

A more efficient solution is to sum up the counts (values) of each element:

sum(counter.values())

In Python 3.x, values() returns a view object of the dict's values.

In Python 2.x, values() returned an actual list. To avoid creating a new list with Python 2.x, use itervalues() instead:

sum(counter.itervalues())
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • No, there is none. `Counter` does not keep track of this information. At least summing the counts is much more efficient than `len(list(counter.elements()))`. – Sven Marnach Mar 31 '11 at 21:12
  • This is (a) more efficient and (b) more succinct than my original method, but it's still ugly. If there's no better way, I suggest that there should be a `Counter.elements_count()` method. – Ram Rachum Mar 31 '11 at 21:19
  • 1
    @cool-RR: Just derive from `Counter` and add that method. Making it O(1) is cumbersome though -- you would basically need to rewrite the whole `Counter` class. – Sven Marnach Mar 31 '11 at 21:22
  • I think Python-ideas is the way to go. – Ram Rachum Mar 31 '11 at 21:25
  • @cool-RR: Well, I was assuming you just want to get the job done :) – Sven Marnach Mar 31 '11 at 21:29
  • Why would you want to update the total sum every time a item is added, that would just make the whole class slower. Doing `sum` once in the end is actually faster. – Jochen Ritzel Mar 31 '11 at 21:49
  • @Jochen: Your point is of course true if you only want to know the number of elements once. If you frequently update a very large `Counter` instance and want to know the number of elements after each update, the situation might be different. – Sven Marnach Mar 31 '11 at 22:54