For the record: this type of function is usually called clamp
(as in a fix), sometimes clip
. The signature you will mostly find for this is clamp(val, minv, maxv)
. If you don't like the idiomatic solution using the min
and max
functions due to utility overhead functions, you can use this solution:
def clamp(val, minv, maxv): return minv if val < minv else maxv if val > maxv else val
Quick health check:
>>> import timeit >>> timeit.timeit("clamp(1, 5, 10)", "def clamp(val, minv, maxv): return min(maxv, max(minv, val))") 1.8955198710000332 >>> timeit.timeit("clamp(1, 5, 10)", "def clamp(val, minv, maxv): return minv if val < minv else maxv if val > maxv else val") 0.5956520039999305
source share