Count the number of occurrences of a value in a list

8

I have list with the following values:

numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]

In Python would have some function to count how many times some value repeats?

For example: I want to know how many times 5 has repeated.

    
asked by anonymous 09.01.2017 / 20:04

2 answers

10

Using Python 2 or 3

Only use the method count()

numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
numeros.count(5)
    
09.01.2017 / 20:07
7

You can use Counter :

import collections
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
repetidos = collections.Counter(numeros)
print(repetidos[5])

See running on ideone .

If you prefer the short form:

print(collections.Counter([5, 3, 1, 2, 3, 4, 5, 5, 5])[5])
    
09.01.2017 / 20:09