I have this:
a = min(max(x, 1), 100)
Is there anything more pythonic?
What about:
a = 1 if x < 1 else 10 if x > 10 else x
It gives the readability that you wanted without the redundancy of the version in your comment. It is verbose because it defines the centre case first and then has to distinguish between the two ends. This way of doing it cuts the ends of first and everything left is in range.
If it's for an array, you could use numpy.clip
.
Otherwise, I think your solution is the best one. Or you could define your own function that does the same for a single element, if you do that at multiple places.
Another option that you might consider more pythonic:
if x > 100:
x = 100
elif x < 1:
x = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With