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