How to count total number of occurrences of an object in a Python list?

PythonServer Side ProgrammingProgramming

You can use the list class count function to count the occurrences of an object in a Python list. Use this only if you want the count of one object only. It finds the total number of the object you pass it in the list it is called on. 


>>> ["red", "blue", "red", "red", "blue"].count("red")

If you want to get the count for all the objects in the list, you'd be better off using Counter from collections. It counts the frequency of all objects in the given list and returns them as a dictionary with the keys as the objects and values as their count in the list. 


from collections import Counter
my_list = ["red", "blue", "red", "red", "blue"]


This will give the output −

Counter({'blue': 2, 'red': 3})
Published on 05-Jan-2018 14:19:46