How to count occurrences of all items in a list in Python

To count the number of occurrences of all elements in a list in Python, use the Counter class from the collections module.

Counter will return a dictionary with the items as keys and the number of occurrences of each as the values.

from collections import Counter

car_brands = ['ferrari', 'bmw', 'mclaren', 'bmw', 'bmw', 'ferrari']

print(Counter(car_brands))
Counter({'bmw': 3, 'ferrari': 2, 'mclaren': 1})