How to Use Counter Function in Python?

In this tutorial, I will explain how to use the counter function in Python. As a software developer, I faced an issue while working on a project for a client in New York where I needed to use the counter function. I explored more about this and I will share my findings in this article. Let us learn more about this topic today.

Counter Function in Python

Python Counter is a subclass of dict that allows you to count the occurrences of elements in an iterable object, such as a list, tuple, or string. It stores the elements as dictionary keys and their respective counts as dictionary values. The Counter class offers various methods to manipulate and analyze the counted data.

Let’s take a look at a simple example to understand how Counter works:

from collections import Counter

names = ['John', 'Emily', 'Michael', 'Emily', 'John', 'Sarah', 'Michael', 'John']
name_counts = Counter(names)
print(name_counts)

Output:

Counter({'John': 3, 'Emily': 2, 'Michael': 2, 'Sarah': 1})

I have executed the above example code and added the screenshot below.

Counter Function in Python

In this example, we have a list of names, and we want to count how many times each name appears. By passing the names list to the Counter constructor, we get a Counter an object that holds the count of each unique name.

Read Interfaces in Python

Example: Analyze Customer Data

Imagine you’re working for a company in the United States that wants to analyze customer data to understand the distribution of customers across different states. You have a list of customer addresses, and you need to count the number of customers in each state. This is where Counter can be incredibly useful.

from collections import Counter

customer_addresses = [
    '123 Main St, New York, NY',
    '456 Elm St, Los Angeles, CA',
    '789 Oak St, Chicago, IL',
    '321 Pine St, Houston, TX',
    '654 Maple St, New York, NY',
    '987 Cedar St, Los Angeles, CA',
    '741 Birch St, Chicago, IL',
    '852 Walnut St, Houston, TX',
    '963 Spruce St, New York, NY'
]

state_counts = Counter(address.split(',')[-1].strip() for address in customer_addresses)
print(state_counts)

Output:

Counter({'NY': 3, 'CA': 2, 'IL': 2, 'TX': 2})

I have executed the above example code and added the screenshot below.

How to Use Counter Function in Python

In this example, we have a list of customer addresses in the format “street, city, state”. We use a generator expression to extract the state from each address and pass it to the Counter constructor. The resulting state_counts object gives us the count of customers in each state.

Check out Access Modifiers in Python

Access Individual Counts

Once you have a Counter object, you can easily access the count of individual elements using the dictionary-like syntax. You can treat the Counter object as a regular dictionary.

print(state_counts['NY'])
print(state_counts['CA'])

Output:

3
2

I have executed the above example code and added the screenshot below.

Use Counter Function in Python

Read How to Use Single and Double Quotes in Python?

Find the Most Common Elements

Python’s Counter provides a convenient method called most_common() that returns a list of the n most common elements and their counts, sorted in descending order by count.

top_states = state_counts.most_common(2)
print(top_states)

Output:

[('NY', 3), ('CA', 2)]

In this example, most_common(2) returns the top 2 states with the highest number of customers.

Check out Python 3 vs Python 2

Advanced Usage of Counter

1. Update Counts

You can easily update the counts in a Counter object by using the update() method. It allows you to add counts from another iterable or dictionary.

additional_addresses = [
    '753 Oak St, San Francisco, CA',
    '159 Pine St, New York, NY',
    '486 Maple St, Chicago, IL'
]

state_counts.update(address.split(',')[-1].strip() for address in additional_addresses)
print(state_counts)

Output:

Counter({'NY': 4, 'CA': 3, 'IL': 3, 'TX': 2})

In this example, we have additional customer addresses that we want to include in the count. By using the update() method, we can easily increment the counts of the corresponding states.

Check out Difference Between “is None” and “== None” in Python

2. Mathematical Operations on Counters

Python’s Counter supports various mathematical operations, such as addition, subtraction, intersection, and union. These operations allow you to combine or compare multiple Counter objects.

counter1 = Counter({'NY': 3, 'CA': 2, 'IL': 2, 'TX': 2})
counter2 = Counter({'NY': 1, 'CA': 3, 'FL': 2})

combined_counter = counter1 + counter2
print(combined_counter)

Output:

Counter({'CA': 5, 'NY': 4, 'IL': 2, 'TX': 2, 'FL': 2})

In this example, we have two Counter objects representing customer counts from different sources. By using the addition operator (+), we can combine the counts from both counters into a new Counter object.

Read How to Comment Out a Block of Code in Python?

Conclusion

In this tutorial, I helped you to learn how to use the counter function in Python. I discussed counter function, examples to analyze customer data , access individual element , finding the most common element and advantages of counter function.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.