-4

I'm looking for a way to count the the number of times that an element appears in a list.

I found a way to do it but I am looking for a short an efficient way to do it.

Example:

Find the number of times the number 5 appears in the list l.

l = [1, 1, 3, 4, 5, 5, 5, 5]

Expected Result would be 4.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
BrockenDuck
  • 220
  • 2
  • 14
  • 3
    Show us what you tried – h4z3 Aug 28 '19 at 14:19
  • If you search in your browser for "Python count items in list", you'll find references that can explain this much better than we can manage here. – Prune Aug 28 '19 at 14:24
  • Possible duplicate of [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – Henry Woody Aug 29 '19 at 00:40

4 Answers4

4

There are many ways:

1. Using list.count (simplest and best if you only care about one element):

print(l.count(5))

2. Using collections.Counter (also simple and best if you care about all elements):

print(Counter(l)[5])

3. Using a list comprehension with len:

print(len([i for i in l if i == 5]))

4. Using a generator expression with sum:

print(sum(i == 5 for i in l))
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    the `sum` version could be rewritten as `sum(i == 5 for i in l)`. – hiro protagonist Aug 28 '19 at 14:24
  • 1
    I expect the list comprehension and the generator expresion to be less efficient and they are obviouslly more cryptic. Would recommend the `count` version if you only care about one element and the `collections.Counter` version if you care about multiple items. – Adirio Aug 28 '19 at 14:28
2

Use list.count:

>>> l = [1, 1, 3, 4, 5, 5, 5, 5]
>>> l.count(5)
4

To find if there is any 5 in the list or not:

>>> l = [1, 1, 3, 4, 5, 5, 5, 5]
>>> bool(l.count(5))
True
Nouman
  • 6,947
  • 7
  • 32
  • 60
1

one way is to use collections.Counter:

from collections import Counter

l = [1, 1, 3, 4, 5, 5, 5, 5]  # find the number of 5

c = Counter(l)
print(c[5])  # 4

this will be more efficient than l.count(5) if you want to know the number of occurrences of the other items. (less efficient if you only care about one item).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

It simple
just do:
l.index(5);

RomanTenger
  • 56
  • 12