Counting Objects Using Python's Counter

Real Python · Intermediate ·💻 AI-Assisted Coding ·4y ago

Key Takeaways

This video demonstrates how to use Python's Counter class from the collections library to count the frequency of items in a sequence, providing a clean and efficient solution to common counting problems in programming. The Counter class is shown to be a powerful tool for handling missing keys, accessing key-value pairs, and determining the most and least common items in a container.

Full Transcript

welcome to counting with python's counter my name is christopher and i will be your guide this course is all about python's counter class in the collections library you'll learn about counting problems in computing how to use the counter class to write less code practical algorithms where the counter class is helpful and multi-sets sample code in this course was tested with python 310. the counter class is mostly unchanged i do use f strings in a couple of places but besides that the information is fairly version agnostic a common problem in computing is determining the frequency of items in a sequence or to put it more simply counting things or groups of things if you're counting one thing you use a variable but if you're trying to count a whole bunch of things or track multiple things then python's counter class can help you do that the first lesson will be on counting problems in the previous lesson i gave an overview of the course in this lesson i'll introduce you to solving counting problems without python's counter class doing it the hard way first my mother would be proud computing is full of counting problems one of the first things you learn to do with a sequence such as a list is to find its length that's a basic counting problem how many things are there in that sequence finding the length of a sequence is only the beginning though what about grouping things together in your data counting these kinds of things is called determining the frequency of an occurrence let's go to the reply and i'll show you what i'm talking about let me start without using any libraries just some straight python data types take the word mississippi what if you wanted to count the occurrences of each of the letters in the word you could create a dictionary then for each letter in the word check if that letter is already in your dictionary if it isn't then create and initialize the key value pair to zero and then either way increment the counting value looking at the result in the dictionary you'll see a key for each unique letter and the corresponding count of the letter as the value one m four i's four s's and two p's by the time you're done you're going to be tired of mississippi i promise initializing a new key in the dictionary can be done in other ways let's skin the proverbial cat what a horrid expression same initial dict same for loop and this time instead of a conditional to initialize the value and a line increment it can be done in a single statement the get method of a dictionary takes a default value parameter so in this case either the letter is fetched and then incremented or 0 is returned and incremented the new value is set into the dictionary at the corresponding key the counter dict now has the same result as before and you could also do it with the default dict class default dict is a specialty dictionary class that lives in the collections module and this time instead of creating an empty dict you create a new default dick class passing in int the hint here is in the class's name it is a dictionary with a default value passing an int means that if a key isn't found create it setting it to an integer the default value for an integer is zero so our new key will be set to zero as before same loop and this time a much easier to read line this is doing the same thing as get before but by using the default dict the default key behavior sets it to zero and then you can increment it looking at the counter you see that it looks a little different as the result isn't a plain old dictionary but a default one the counts inside are the same and as default dict inherits from dict anything you can do with the base class you can do with this fancier one okay i think you've got a taste for the problem as this course is titled counting with python's counter it shouldn't be a surprise that the next lesson is on using the counter class in the previous lesson i showed you a counting problem and tooled a solution by hand in this lesson i'll show you how to use python's counter class to make this simpler the counter class is a member of the collections library and like several of the other classes within that library it is based on a dictionary in this case the keys are the instances of things being counted while the corresponding values are the count of those things you came here to code let's dive into the rebel think back to the mississippi letter counting problem in the previous lesson here is a much shorter version yep that's it creating a counter object results in counting whatever iterable is passed in a string in an iterable context gives each letter inside of the string so passing a string to counter counts each of the unique letters counters can also take lists passing in the list in this case the list is turning the string into the interval of letters and passing the list into counter ends up in the same result you can also pass in dictionaries in this case the key value pairs indicate objects being counted and their corresponding counts essentially the data structure our results got stored in back when a variety of cats were in danger all right i'll stop with the cat jokes i promise you can also pass in named arguments to counter each named argument is treated as a string with the corresponding value being the count alternatively you can give it a set remember that sets are also constructed based on iteration but they can only hold one instance of each thing in the iteration creating a set from mississippi iterates on the letters keeping only the unique values create a counter based on the set results in a count of 1 for each of the letters counters are just dictionaries you can use any hashable item as a key and store any value the only caveat is that if the value is not an integer you won't be able to increment that count later so although it won't stop you from storing anything if you want to take advantage of some of the key additional features of counter you really only want to store integers let me show you another example using arguments here i'm storing integers and one of them is negative what does -15 tomatoes mean well maybe you owe your neighbor that many and this counter is tracking what's in your fridge you know how a second ago i mentioned you can increment the counter later well it's later little deja vu and one mississippi and now with the counter instance i can change values by calling the update method like the initializer update takes any iterable iterating on ohio adds two o's an h and an i to the count you can see the difference here you can also call update with a dictionary that's a lot of eyes notice updating with -5 h's leaves minus 4 h's in the counter you're probably starting to see the pattern here you can update with arguments that's five more s's and five more p's as a counter is just a special type of dictionary you can access a key with a subscript which means you can loop over your counter likewise counters have a keys method so that you can get at the keys in your counter and a values method and an items method all your inherited dictionary goodness one behavior of counters that's a little different than dictionaries is when you ask for a key that isn't there instead of getting a key error you get the count there are zero a's in mississippi well mississippi plus a bunch of other things i did but there's no ways there note that this is case sensitive nothing i've typed has a capital letter in it so asking for one is going to return zero another service the counter offers is information on how common the elements in the container are consider a counter tracking how many pieces of fruit got sold the most common method returns a list of tuples the tuples are the key value pairs in the counter and the list is in order of frequency apples are most common tomatoes the least you can pass an argument to most common to limit how many items come back this is just the most popular type of fruit and that is the two most popular passing in none is the same as no argument you get back the whole list passing in a number bigger than the number of items in the container returns the whole list as well what about the least common items well there's no method for that but you can get at it with a bit of work i'll start by capturing the most common remember that this returns a list and then i call the reverse method on that list voila you've got it all backwards as intended there's more than one way to oh wait i made a promise anyhow uh you can also call the built in function reversed this gives you a list reverse iterator which you can put in a for loop or do whatever else you normally do with an iterator i'm just going to stick it in the list so you can see the results one last way to accomplish the same thing this is slightly harder to read but a fairly common shortcut it's called the negative slice this is a trick that works with the slicing operator to create a reversed list in place see the description below for an article with more details on this now you've seen how to use the class next up i'll show you some practical applications

Original Description

Counting several repeated objects at once is a common problem in programming. Python offers a bunch of tools and techniques you can use to approach this problem. However, Python’s Counter from collections provides a clean, efficient, and Pythonic solution. This dictionary subclass provides efficient counting capabilities out of the box. Understanding Counter and how to use it efficiently is a convenient skill to have as a Python developer. This is a portion of the complete course, which you can find here: https://realpython.com/courses/counting-python-counter/ The rest of the course covers how to: - Use Counter in several practical examples - Use additional methods like .most_common and .items - Implement Counter instances as multisets
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches how to use Python's Counter class to count the frequency of items in a sequence, providing a clean and efficient solution to common counting problems in programming. The Counter class is shown to be a powerful tool for handling missing keys, accessing key-value pairs, and determining the most and least common items in a container. By watching this video, viewers will learn how to create a Counter object, update it using the update method, and access key-value pairs using the m

Key Takeaways
  1. Create a dictionary to count the occurrences of each letter in a word
  2. Use the get method to initialize a new key in the dictionary with a default value of 0
  3. Use the defaultdict class to create a dictionary with a default value of 0
  4. Increment the count for each letter in the word
  5. Create a Counter object from a container
  6. Pass an iterable to Counter
  7. Pass a dictionary to Counter
  8. Pass named arguments to Counter
  9. Update a Counter using the update method
  10. Use the most_common method to get a list of tuples with key-value pairs in order of frequency
💡 The Counter class in Python's collections module provides a clean and efficient solution to common counting problems in programming, handling missing keys and providing methods for accessing key-value pairs and determining the most and least common items in a container.

Related Reads

📰
Cursor Pricing 2026: Free vs Pro vs Ultra — Which Plan?
Learn how to choose the right Cursor plan for your coding needs and budget, and discover how this Agentic AI coding tool can boost your productivity
Dev.to AI
📰
enable Consistent AI Coding with Persistent Context Layers
Learn how persistent context layers can improve AI coding consistency and reliability
Dev.to AI
📰
LeetCode Isn’t Dead. Your Interview Prep Strategy Is.
Update your interview prep strategy to focus on practical skills and real-world problem-solving, as LeetCode-style interviews are evolving
Medium · Programming
📰
Build a UGC video moderation pipeline with FFmpeg + NudeNet
Learn to build a UGC video moderation pipeline using FFmpeg and NudeNet to ensure safe and respectful user-generated content
Dev.to · Mason K
Up next
Copilot Cowork: Setup, Skills, Plugins & Pricing
Matt Tutorials
Watch →