Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check how many times an element exists in a list [duplicate]

Tags:

python

list

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?

like image 324
g0str1d3r Avatar asked Nov 23 '13 19:11

g0str1d3r


2 Answers

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
like image 187
Jud Avatar answered Sep 30 '22 04:09

Jud


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}
like image 37
Akavall Avatar answered Sep 30 '22 06:09

Akavall