Counter ExampleUse the Counter object from the collections module. Count frequencies of values.
Python
Counter. Often in Python programs we want to record the number of uses, hits, or instances of something. We collect (count) frequencies.
Dictionary Counter info. 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.
Simple example. To begin, we import Counter and create a Counter named "x." We add to indexes with the counter, and print the Counter directly to the console.
Console, print
Info The Counter stores the values we have incremented, and when we display its contents, we see what we have added. from collections import Counter x = Counter() # Add 1 at index 0. x += 1 print(x) # Add more to the counter, and display it. x += 1 x += 1 x += 1 print(x)
Counter({0: 1}) Counter({2: 2, 0: 1, 3: 1})
Complex example. For a more complex example, we use the Counter with range loops. We add to the counter based on ranges of integers. The counts accumulate.
range
Detail We can display values by accessing each key, or we can display the entire counter by passing it to the print method.
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)
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.
from collections import Counter freqs = Counter() print(freqs) # Three birds are added. freqs["bird"] += 1 freqs["bird"] += 1 freqs["bird"] += 1 print(freqs) # One bird was removed. freqs["bird"] -= 1 print(freqs) # Four birds were counted. freqs["bird"] = 4 print(freqs)
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.