For more information on concepts covered in this lesson, you can check out Reverse Strings in Python: reversed(), Slicing, and More.
Using Python's Counter Class
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.
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
01:48 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.
02:19 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.
You know how a second ago, I mentioned you can increment the counter later? Well it’s later. A little deja vu, and one Mississippi. And now with the
Counter instance, I can change values by calling the
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
KeyError, you get the count. There are zero
mississippi plus a bunch of other things I did, but there’s no
05:34 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.
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?
There’s more than one way to—oh wait, I made a promise. Anyhow, you can also call the built-in function
reversed(). This gives you a
list_reverseiterator, 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 (
[::-1]) to create a reversed list in place. See the description below for an article with more details on this.
Become a Member to join the conversation.