zach zach - 2 months ago 24
Python Question

number of values in a list greater than a certain number

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
#list comprehension of values of j > 5
x = [i for i in j if i>5]
#value of 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?


You could do something like this:

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

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)