7

Let's say I have this list:

a = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1]

I want to know how many elements are there bigger than 7. The result should be 3. Is there an elegant way to do this in Python? I tried with count but it won't work.

jamylak
  • 128,818
  • 30
  • 231
  • 230
otmezger
  • 10,410
  • 21
  • 64
  • 90

3 Answers3

19
>>> a = [1.1 , 2 , 3.1 , 4 , 5 , 6 , 7.2 , 8.5 , 9.1]
>>> sum(x > 7 for x in a)
3

This uses the fact that bools are ints too.

(If you oppose this because you think it isn't clear or pythonic then read this link)

Community
  • 1
  • 1
jamylak
  • 128,818
  • 30
  • 231
  • 230
2

Even shorter, using numpy:

sum(np.array(a)>7)
Noam Peled
  • 4,484
  • 5
  • 43
  • 48
0

write a function that return you count of elements greater than specific number.

def get_max_count(l, num):
    count = 0

    for x in l:
        if x > num:
            count+=1
    return count

l = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1]
print get_max_count(l=l, num = 7)
Abdul Majeed
  • 2,671
  • 22
  • 26