I have a list like this:
[5,6,7,2,4,8,5,2,3]
and I want to check how many times each element exists in this list.
what is the best way to do it in Python?
The count()
method counts the number of times an object appears in a list:
a = [5,6,7,2,4,8,5,2,3]
print a.count(5) # prints 2
But if you're interested in the total of every object in the list, you could use the following code:
counts = {}
for n in a:
counts[n] = counts.get(n, 0) + 1
print counts
You can use collections.Counter
>>> from collections import Counter
>>> Counter([5,6,7,2,4,8,5,2,3])
Counter({2: 2, 5: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With