How to count the occurrences of all list items in list Python?


I want to count the occurrences of all list items in a list. I did it with count() as below

a = [1,2,2,2,4,5]

for i in a:
   print(a.count(i))

But it's taking so much time when the data is huge. Is there any other way to do this?

1 Answer

4 years ago by

To count the occurrences of all items in a list, you can use counter() instead of a loop.

from collections import Counter
 a = [1,2,3,4,1]
 print(Counter(a))

Check Output here

4 years ago by Divya