Python Counter Example

Use the Counter object from the collections module. Count frequencies of values.

Counter. Often in programs we want to record the number of uses, hits, or instances of something. We collect (count) frequencies.

With Counter, from the collections module, we can do this with minimal set-up code. We access the Counter like a list, but can count strings or numbers.

First example. Here we import Counter from the collections module. We then use range loops to count numbers in the Counter. The counts accumulate.

Display: We can display values by accessing each key, or we can display the entire counter by passing it to the print method.

Python program that uses Counter from collections import Counter # Create new counter. freqs = Counter() # Add to the counter based on ranges of numbers. for i in range(0, 10): freqs[i] += 1 for i in range(0, 5): freqs[i] += 1 for i in range(0, 2): freqs[i] += 1 # Display counter contents. for i in range(0, 10): print(f"Value at {i} is {freqs[i]}") # The counter can be displayed directly. print(freqs) Output Value at 0 is 3 Value at 1 is 3 Value at 2 is 2 Value at 3 is 2 Value at 4 is 2 Value at 5 is 1 Value at 6 is 1 Value at 7 is 1 Value at 8 is 1 Value at 9 is 1 Counter({0: 3, 1: 3, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})

Strings. We can do more things with a counter than just increment by one. We can decrement. Or we can assign values. We can also use string keys in the counter.Strings
Python program that uses Counter with strings from collections import Counter freqs = Counter() print(freqs) # Three birds are born. freqs["bird"] += 1 freqs["bird"] += 1 freqs["bird"] += 1 print(freqs) # One bird was killed. freqs["bird"] -= 1 print(freqs) # Four birds were counted. freqs["bird"] = 4 print(freqs) Output Counter() Counter({'bird': 3}) Counter({'bird': 2}) Counter({'bird': 4})

A summary. The collections module in Python contains useful collections like Counter. For recording the frequencies of numbers and strings (and other things) we can use Counter.

A major benefit. For Counter, a major benefit is that less initialization logic is needed. So we can spend more attention on counting rather than dealing with a dictionary.Dictionary
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to