🐍 Python’s collections.Counter: Simplify Your Data Analysis

Elshad Karimov
2 min read1 day ago
Photo by Ales Nesetril on Unsplash

Have you ever needed to count the occurrences of items in a list or quickly find the most common elements in your data? Meet Python’s collections.Counter, a built-in tool that makes these tasks ridiculously easy! Let’s dive into how it works and why it’s a must-know for any Python enthusiast.

🤔 What is Counter?

The Counter class is part of the collections module and is designed for counting hashable objects. Think of it as a dictionary with a twist: the keys are the elements, and the values are their counts.

Here’s how to get started:

from collections import Counter

🚀 Practical Examples

1. Counting Items in a List

Let’s say you have a list of fruits, and you want to know how many times each fruit appears:

from collections import Counter

fruits = ["apple", "banana", "orange", "apple", "banana", "apple"]
fruit_count = Counter(fruits)

print(fruit_count)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})

Now you know that apples are the clear winner here!

2. Finding the Most Common Elements

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet