Check how many items from the list fall in the specified range (Python)

I have a list of elements (integers), and I need to quickly check how many elements from this list fall in the specified range. An example is below.

range from 34 to 566

l = [9,20,413,425]

The result is 2.

I can of course use a simple loop for this purpose and compare each element with a minimum and maximum value (34 <x <566), and then use a counter if the statement is true, however I think this can be a much easier way to do this this is possibly with a nice single layer.

+5
source share
3 answers
>>> l = [9,20,413,425]
>>> sum(34 < x < 566 for x in l)
2
+12
source

len([x for x in l if x > 34 and x < 566])

+8
source

Well, I'm not sure if this is good, but this is one line; -)

len(set([9,20,413,425]).intersection(range(34,566)))
+2
source

All Articles