zach - 3 months ago 33

Python Question

I have a list of numbers and I want to get the number of times a number appears in a list that meets a certain criteria. I can use a list comprehension (or a list comprehension in a function) but I am wondering if someone has a shorter way.

`# list of numbers`

j=[4,5,6,7,1,3,7,5]

#list comprehension of values of j > 5

x = [i for i in j if i>5]

#value of x

len(x)

#or function version

def length_of_list(list_of_numbers, number):

x = [i for i in list_of_numbers if j > number]

return len(x)

length_of_list(j, 5)

is there an even more condensed version?

Answer

You could do something like this:

```
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3
```

It might initially seem strange to add `True`

to `True`

this way, but I don't think it's unpythonic; after all, `bool`

is a subclass of `int`

in all versions since 2.3:

```
>>> issubclass(bool, int)
True
```