WlJs
WlJs

Reputation: 1007

Check how many elements from a list fall within a specified range (Python)

I have a list of elements (integers) and what I need to do is to quickly check how many elements from this list fall within a specified range. The example is below.

range is from 34 to 566

l = [9,20,413,425]

The result is 2.

I can of course use a simple for loop for the purpose and compare each element with the min and max value (34 < x < 566) and then use a counter if the statement is true, however I think there might be a much easier way to do this, possibly with a nice one-liner.

Upvotes: 7

Views: 3614

Answers (3)

Nolen Royalty
Nolen Royalty

Reputation: 18633

>>> l = [9,20,413,425]
>>> sum(34 < x < 566 for x in l)
2

Upvotes: 14

snies
snies

Reputation: 3521

well i am not sure this is nice, but it's one line ;-)

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

Upvotes: 2

gefei
gefei

Reputation: 19766

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

Upvotes: 9

Related Questions