pythonrange

How to force a value to be within a range?


What is the most "pythonic" way to do this?

x = some_value
bounds = [lower_bound, upper_bound]

if x < bounds[0]:
    x = bounds[0]
if x > bounds[1]:
    x = bounds[1]

Solution

  • ...and sometimes get carried away with finding a tricky way to do do something in one line.

    The most important thing when programming is that you really understand the problem you want to solve. And then you want to write code, that can be read. So, pythonic does not mean it is a one-liner...

    And this is not ugly or bad Python:

    if x < lb:
        x = lb
    elif x > ub:
        x = ub
    

    And this is the way I would suggest to write what Naman Sogani suggested.

    _, x, _ = sorted([lb, x, ub])