Python Forum
What's the use case of collections.counter?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What's the use case of collections.counter?
#1
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
Reply
#2
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.
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  cs.collections error DaveG 7 1,688 Apr-06-2022, 04:18 PM
Last Post: Larz60+
  Switch case or match case? Frankduc 9 4,390 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  Trying to understand how isinstance(values, collections.Iterable) work. quazirfan 7 4,098 Aug-10-2021, 08:10 AM
Last Post: snippsat
  AttributeError: 'collections.OrderedDict' object has no attribute 'value_counts Kristenl2784 4 7,270 Jul-17-2020, 01:50 AM
Last Post: palladium
  collections.OrderedDict Bert123456 2 1,748 Jul-09-2020, 08:51 PM
Last Post: Bert123456
  AttributeError: module 'collections' has no attribute 'namedtuple' epgs1975 2 10,242 May-04-2020, 08:10 PM
Last Post: epgs1975
  Problem with importing and using collections module pythomdummy 3 5,738 Nov-14-2019, 08:48 AM
Last Post: Gribouillis
  Please, advise collections for my task AlekseyPython 1 2,054 Sep-11-2019, 12:44 PM
Last Post: perfringo
  Drills/Exercises for collections, itertools, and common built-in data structures? Cranberry 2 3,328 Apr-26-2018, 05:43 PM
Last Post: Cranberry

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020