Important Python Counter Object Attributes

This blog post will list some important Python counter object attributes. In some of my blog posts, counter objects are a main part of the example. It is a type of dataset that is provided with the collections module in most recent versions of Python. That type of dataset provides an alternative to dictionaries, tuples, and lists. The counter class is used to count hashable objects. A hash table is created from all iterables when called.

Returns a view of all unique elements.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.keys())

Returns counts of each element.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.values())

Returns elements and counts pairs.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.items())

Returns the most common elements and counts as a list of tuples.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.most_common(2))

Leave a Reply