Python Collections: Counter

Many times we need to keep track of frequencies of unique keys. We can always use a dictionary but counter is more appropriate for its brevity. Python collections define the counter class. Counter works on any iterator and generates a count of elements. So it has a natural use case on the list 🙂

from collections import Counter


def checkDiff(list1, list2):
    if (Counter(list1) - Counter(list2)) == {}:
        print("Yes")
    else:
        print("No")

    print(Counter(list1))
    print(Counter(list2))
    print(Counter(list2) + Counter(list1))


checkDiff(["a", "a"], ["a", "b"])

Result

$ python counter.py 
No
Counter({'a': 2})
Counter({'a': 1, 'b': 1})
Counter({'a': 3, 'b': 1})

The above code checks if list2 has all elements of list1. Since frequency of a is two in list1 & one in list2, it prints No.

Reference

https://docs.python.org/dev/library/collections.html#collections.Counter

Written with StackEdit.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.