๐Ÿ““๐ŸŒฑ๐Ÿ’ป GuidoPercu.dev

Python collections.Counter

Published on

From Luciano Ramalho “Fluent Python” book:

Fluent Python Book from O’Reilly

collections.Counter A mapping that holds an integer count for each key. Updating an existing key adds to its count. This can be used to count instance of hashable objects (the keys) or as a multiset – a set that can hold several occurences of each element. Counter implements + and - operators to combine tallies, and other useful methods such as most_common([n]), which returns an ordered list of tuples with the n most common items and their counts; see the documentation. Here is Counter used to count letters in words:

We can use this data structure to check if two strings are anagrams:

Want to know the most frequent words of a song? No problem!

Computer biologist? How about get the frequency of nucleotides from a genome fasta file?

More information: