In this article, you will learn how to use Python counters.
How to Use Python Counters
The collections module in Python provides a Counter class which is used to count the number of occurrences of elements in a list, tuple, or any other iterable object.
Here’s how you can use it:
Import the collections module
Create a Counter object
# Create a Counter object from a list my_list = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3] counter = collections.Counter(my_list) # Create a Counter object from a string my_string = "this is a simple sentence" counter = collections.Counter(my_string)
Access the count of elements
# Access the count of a specific element print(counter) # Access the count of all elements print(counter)
Perform operations with counters
# Add two counters counter1 = collections.Counter(a=3, b=1) counter2 = collections.Counter(a=1, b=2) result = counter1 + counter2 print(result) # Subtract two counters counter1 = collections.Counter(a=3, b=1) counter2 = collections.Counter(a=1, b=2) result = counter1 - counter2 print(result)
Note that the counters are unordered, so the order of elements may not be the same as the order in the original list or string.