Counting With Python's Counter (Summary)
When you need to count several repeated objects in Python, you can use Counter
from collections
. This class provides an efficient and Pythonic way to count things without the need for using traditional techniques involving loops and nested data structures. This can make your code cleaner and faster.
In this video course, you learned how to:
- Count several repeated objects using different Python tools
- Create quick and efficient counters with Python’s
Counter
- Retrieve the most common objects in a particular counter
- Update and manipulate object counts
- Use
Counter
to facilitate further computations - Implement
Counter
instances as multisets
For more information on concepts covered in this course, you can check out:
- Reverse Strings in Python: reversed(), Slicing, and More
- Python’s collections: A Buffet of Specialized Data Types
- Dictionaries in Python
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00
In the previous lesson, I showed you how to use the Counter
class as a multiset. In this lesson, I’ll summarize the course. In this course, I showed you all about counting problems and how to use Python’s Counter
class to help you solve those kinds of problems.
00:16
Remember that you can initialize the counter with sequences, dictionaries, and arguments, as well as other Counter
classes. Once you’ve initialized the counter, you can get the most frequent items in the class by calling the .most_common()
method. You can also get the contents using .keys()
, .values()
, .items()
, and .elements()
.
00:41
In this course, I covered several different practical applications of the Counter
class, including counting letter frequency, building histograms, determining the statistical mode, counting file types, and building shopping carts.
00:57 And finally, I went a little math geek and described multisets and their operations and how you can use a counter to implement them.
01:07 That’s all I have on counters. Thanks for your attention. I hope you enjoyed the course. Pause for one Mississippi, two Mississippi, three Mississippi, and fade to black.
Become a Member to join the conversation.
James on March 10, 2022
Nicely done. Examples are good.