Count the number of occurrences of a value in a list

Asked

Viewed 23,324 times

11

I have a 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 the 5 repeated.

2 answers

15


Using Python 2 or 3

Only use the method count()

numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
numeros.count(5)

15

  • Bacana, the Counter returns a structure similar to a dict with key value assignment...

  • I believe this should be the accepted answer, as it is much more general than the @LINQ response

  • 1

    @Luizangioletti "much more general" refers to being able to iterate and take the amount of repetitions of each? (This seems to me the only difference of both)

  • 1

    @Luizangioletti, maybe the case of the AP is just to count a single el specific number and then he will forget the collection. In that case, the LINQ response will be more appropriate than that. If it is necessary to make multiple counts there is strategy adds much more than the other

Browser other questions tagged

You are not signed in. Login or sign up in order to post.