6

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
  • 8,523
  • 3
  • 16
  • 34
g0str1d3r
  • 96
  • 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,068
  • 1
  • 7
  • 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
  • 76,296
  • 45
  • 192
  • 242