7

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?

MendelG
  • 14,885
  • 4
  • 25
  • 52
g0str1d3r
  • 106
  • 1
  • 1
  • 11

2 Answers2

14

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
Jud
  • 1,158
  • 1
  • 8
  • 17
  • Why is `total = counts.get(n,0)` included? I get the same result either way with, or without it, so it seems like an extra step. – Puhtooie Dec 18 '18 at 21:47
  • You're right, it is a superfluous item. I'll edit to correct. – Jud Dec 19 '18 at 22:12
9

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}
Akavall
  • 82,592
  • 51
  • 207
  • 251