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

Python Methods and Functions

You can use the list class count function to count the occurrences of an object in a Python list. Only use this if you only want to read one object. It finds the total number of the object you are passing in the list to which it is being called. 


Example

 & gt; & gt; & gt; ["red", "blue", "red", "red", "blue"]. count ("red") 3 

If you want to get a count for all objects in the list, you better use counter from collections. It counts the frequency of all objects in the given list and returns them as a dictionary with keys as objects and values ​​as their number in the list.



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



Output

This will give the output &


< ins class = "adsbygoogle" style = "display: inline-block; width: 336px; height : 280px" data -ad-client = "ca-pub-6959883099270890" data-ad-slot = "6928654010">

 Counter ({'blue': 2,' red': 3}) 







Tutorials