[Python Tips] Counter
Counter
Counter is a collections object that keeps count of how many times similar values are found. Counter is part of the collections module and is a default package, so you do not need to install it.
The most commonly used function is ironically most_common(), which returns the most frequently found values.
Let's go through an example and it should make a lot of sense.
Example
import collections
c = collections.Counter()
c.update('I know it is wet and the sun is not sunny, but we can have lots of good fun that is funny')
c.most_common(3)
The output should look like this:
[(' ', 21), ('n', 10), ('t', 8)]
The most common occurrence is the space coming in at 21 times, followed by n for 10 times and t 8 times.
If you just print(c) the counter object you will see this:
Counter({' ': 21, 'n': 10, 't': 8, 'o': 6, 's': 6, 'u': 5, 'i': 4, 'e': 4, 'a': 4, 'w': 3, 'h': 3, 'f': 3, 'd': 2, 'y': 2, 'I': 1, 'k': 1, ',': 1, 'b': 1, 'c': 1, 'v': 1, 'l': 1, 'g': 1})
You can also interact with a counter using dictionary calls, like the following:
c['n']
returns 10.
Counters also expose an elements() function that allows you to iterate throughout the values.
for value in c.elements():
print(value)
Counter Math
Counters can be combined with other counters, using +, -, &, and |.
+ and - work as expected, it combines or subtracts the elements of two counters.
& returns the insection of two counters, the minimum value from both counters.
| returns the union of the two counters, the maximum value from both counters.
c3 = c1 + c2
c3 = c1 - c2
c3 = c1 & c2
c3 = c1 | c2
My Python Tips Series
Leave [Python Tips] Counter to:
Read more #programming posts
Best Posts From Marky
We have not curated any of themarkymark's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Marky
- Tan Stack Scanner
- New LLM benchmark: llmtester
- Receive proactive alerts when your openclaw instance is unavailable
- My two favorite Openclaw hacks
- If you are running openclaw, make sure you are updated.
- Some things I wish someone told me when I setup Openclaw
- If you are running openclaw, make sure you are updated.
- Hive Hot or Not improvements
- Hive Hot or Not!
- Block Bandits update