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. 

example

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

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. 

example

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

Output

This will give the output −

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