Take the 2-minute tour ×

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?

share|improve this question
add comment

4 Answers

up vote 22 down vote accepted

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)
share|improve this answer
+1 This is a really good solution. –  jamylak May 10 '12 at 23:06
@jamylak, why is this better than Greg Hewgill's? While it is interesting and correct, it seems much less intuitive and less obvious for someone else reading the code. –  TJD May 10 '12 at 23:07
@TJD Didn't say it was better but I like it more. –  jamylak May 10 '12 at 23:09
@senderle: (Greg's previous deleted answer. I added a new answer that will work. :) –  Greg Hewgill May 10 '12 at 23:09
sum(1 for i in j if i > 5) would be a bit more explicit, if that is intended :) The sum(1 for ... if ...) can also be hidden away in a count function. –  Niklas B. May 10 '12 at 23:14
show 2 more comments

if you are otherwise using numpy, you can save a few strokes, but i dont think it gets much faster/compact than senderle's answer.

import numpy as np
j = np.array(j)
sum(j > i)
share|improve this answer
add comment

You can create a smaller intermediate result like this:

>>> len([1 for i in j if i > 5])
share|improve this answer
Or sum(1 for i in j if i > 5) so you don't have to load the list into memory. –  jamylak May 10 '12 at 23:14
add comment

A (somewhat) different way:

reduce(lambda acc, x: acc + (1 if x > 5 else 0), j, 0)

share|improve this answer
add comment

Your Answer


