Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking number of elements in Python's `Counter`

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.

like image 673
Ram Rachum Avatar asked Oct 11 '22 09:10

Ram Rachum


1 Answers

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())
like image 122
Sven Marnach Avatar answered Oct 18 '22 23:10

Sven Marnach