Ishan Bhatt
Ishan Bhatt

Reputation: 10269

Generating range/interval from a tuple

I have a list and a tuple like below,

l = [3,5,7,8]
t = (5,15)

I want to check whether each element of the list falls in the range specified by the tuple. So, here 7,8 is the answer. I came up with the following one, but I am sure there is a better way.

for ele in l:
    if ele > t[0] and ele < t[1]:
        print "Founde it", ele

Is there a way to convert it into range/interval and check directly? Or any one liner ?

Upvotes: 0

Views: 1168

Answers (2)

emre.
emre.

Reputation: 1296

Using list comprehension might be better, or filter and lambda.

[num for num in l if t[0] < num < t[1]]

or

filter(lambda n: t[0] < n < t[1], l)

Upvotes: 0

Avi&#243;n
Avi&#243;n

Reputation: 8396

You can use list comprehension as follows:

print [ele for ele in l if ele > t[0] and ele <t[1]]

This outputs 7 and 8.

Upvotes: 1

Related Questions