You can Count elements in a list with collections Counter in Python. Counter is a subclass of dict that’s specially designed for counting hashable objects in Python. It’s a dictionary that stores objects as keys and counts as values.
Python Counter list
Simple example code get list count.
Counter object is created by passing a list to
collections.Counter(). In python, a list is an iterable object. The elements in the list are given to the counter and it will convert it.
import collections l = ['a', 'a', 'a', 'a', 'b', 'c', 'c'] c = collections.Counter(l) print(c) print(type(c)) print(issubclass(type(c), dict))
You can also use
dict methods such as
print(c.keys()) # dict_keys(['a', 'b', 'c']) print(c.values()) # dict_values([4, 1, 2]) print(c.items()) # dict_items([('a', 4), ('b', 1), ('c', 2)])
Do comment if you have any doubts or suggestions on this Python counter topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.