Python Forum

Full Version: What's the use case of collections.counter?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I came across this module and I wonder why I would use it.
You can just use list.count to count elements in iterables.

c = Counter(['egg', 'ham'])
print(c['bacon'])

d = ['egg', 'ham']
print(d.count("bacon"))
I'd like to be more informed on this. Dodgy
Basically the equivalent of Count using the count method runs in quadratic time. If you're not familiar with the that terminology, take a look at https://python-forum.io/Thread-Efficiency-Crash-Course
Feel free to ask any followup questions.
The quick and dirty of it is that the count builtin is great for counting the presence of a single object. It does it in linear time and this is the best it gets. However if you want to count all items and use the same technique it becomes quadratic. The collections.Counter version does basically exactly what I showed in my reply to the post Mic linked; dictionary counting all items in linear time.