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.

2
  • I raised the subject on Python-ideas and Raymond Hettinger said a Counter.elements_count() method might be added. Python issue: bugs.python.org/issue11733 Commented Mar 31, 2011 at 22:16
  • This idea was rejected but the issue raised looks slightly different from what the OT is asking about. Commented Jul 26, 2019 at 16:15

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

7 Comments

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())).
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.
@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.
I think Python-ideas is the way to go.
@cool-RR: Well, I was assuming you just want to get the job done :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.