34

Is there a built-in function for this in Python 2.6?

Something like:

clamp(myValue, min, max)
Amro
  • 122,595
  • 25
  • 236
  • 442
Joan Venge
  • 292,935
  • 205
  • 455
  • 667

3 Answers3

61

Numpy's clip function will do this.

>>> import numpy
>>> numpy.clip(10,0,3)
3
>>> numpy.clip(-4,0,3)
0
>>> numpy.clip(2,0,3)
2
Richard
  • 50,293
  • 28
  • 163
  • 235
  • 1
    This seems to be extremely slow, though. I'm guessing it's because this function was meant for arrays. – Micael Jarniac Feb 18 '22 at 18:35
  • @Micael: Numpy is always meant for arrays, where it works faster for than any pure-Python alternative. If a person is worrying about the speed of pure-Python it's usually an indication they need to redesign to use arrays, offload, or switch languages. – Richard Feb 18 '22 at 20:27
52

There's no such function, but

max(min(my_value, max_value), min_value)

will do the trick.

Sven Marnach
  • 530,615
  • 113
  • 910
  • 808
  • 13
    I always like to order it like, min(max(low, value), high). And think of it like low < value < high. Then it also reads like a "min-max" function minmax(low, value, high) – johnb003 Jun 10 '20 at 19:15
10

I think the question is answered but here's an alternative DIY solution if anyone needs it:

def clip(value, lower, upper):
    return lower if value < lower else upper if value > upper else value

(Slightly faster than @Sven Marnach's answer - even when in bounds).

Bill
  • 8,217
  • 4
  • 52
  • 75