37

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

Something like:

clamp(myValue, min, max)
Amro
  • 123,847
  • 25
  • 243
  • 454
Joan Venge
  • 315,713
  • 212
  • 479
  • 689

3 Answers3

62

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
  • 56,349
  • 34
  • 180
  • 251
  • 2
    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
58

There's no such function, but

max(min(my_value, max_value), min_value)

will do the trick.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 15
    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
11

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
  • 10,323
  • 10
  • 62
  • 85