Check if a value is between a pair of values ​​in a tuple?

Is there an efficient way (good syntax) to check if a value is between two values ​​contained in a tuple?

The best I could come up with was:

t = (1, 2) val = 1.5 if t[0] <= val <= t[1]: # do something 

Is there a better way to write a conditional expression?

+6
source share
2 answers

No, there is no syntax highlighted, using sequential comparisons is the right way to do this already.

One “subtlety” that I can offer is to use decompression first, but this is just the readability of the glaze:

 low, high = t if low <= val <= high: 

If you use the tuple subclass created by collection.namedtuple() , you can of course use the following attributes:

 from collections import namedtuple range_tuple = namedtuple('range_tuple', 'low high') t = range_tuple(1, 2) if t.low <= val <= t.high: 
+7
source

You can make your own sugar:

 class MyTuple(tuple): def between(self, other): # returns True if other is between the values of tuple # regardless of order return min(self) < other < max(self) # or if you want False for MyTuple([2,1]).between(1.5) # return self[0] < other < self[1] mt=MyTuple([1,2]) print mt.between(1.5) # True 
+1
source

All Articles