Counting Tips

Learn the appropriate use of counter in your program.

Count with defaultdict

When we count the number of occurrences of a particular item in an iterable (say, a specific character in a string), we use an integer number as a counter. When the iterable consists of heterogeneous items and we know the number of their types ahead of time, we can use a list of counters, especially if the item types map nicely to list indexes. If the number of types is large or unknown, a dictionary is the best counting tool. We iterate through the iterable and check if we’ve seen the next item before. If so, we increment its counter in the dictionary. If not, we create a new dictionary item for the new item in the iterable and increment it anyway:

Get hands-on with 1200+ tech skills courses.