Mantis Toboggan Mantis Toboggan - 3 years ago 181
Python Question

How to limit a number to be within a specified range? (Python)

I want to limit a number to be within a certain range. Currently, I am doing the following:

minN = 1
maxN = 10
n = something() #some return value from a function
n = max(minN, n)
n = min(maxN, n)

This keeps it within
, but it doesn't look very nice. How could I do it better?

PS: FYI, I am using Python 2.6.

Answer Source
def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

or functionally equivalent:

clamp = lambda n, minn, maxn: max(min(maxn, n), minn)

now, you use:

n = clamp(n, 7, 42)

or make it perfectly clear:

n = minn if n < minn else maxn if n > maxn else n

even clearer:

def clamp(n, minn, maxn):
    if n < minn:
        return minn
    elif n > maxn:
        return maxn
        return n
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download