Is there an efficient way (nice syntax) to check if a value is between two values contained in a tuple?
The best thing I could come up with is:
t = (1, 2)
val = 1.5
if t[0] <= val <= t[1]:
# do something
Is there a nicer way to write the conditional?
No, there is no dedicated syntax, using chained comparisons is the right way to do this already.
The one 'nicety' I can offer is to use tuple unpacking first, but that's just readability icing here:
low, high = t
if low <= val <= high:
If you are using a tuple subclass produced by collection.namedtuple()
you could of course also use the attributes here:
from collections import namedtuple
range_tuple = namedtuple('range_tuple', 'low high')
t = range_tuple(1, 2)
if t.low <= val <= t.high:
You could 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With