8

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?

0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
You're right, it is a superfluous item. I'll edit to correct.
10

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}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.