More python alternative to get value in range not using min and max

I have it:

a = min(max(x, 1), 100) 

Is there anything more pythonic?

+5
source share
5 answers

What about:

 a = 1 if x < 1 else 10 if x > 10 else x 

This gives the readability you wanted without the redundancy of the version in your comment. This is verbose, because first he defines the central case, and then he must distinguish between the two ends. This way of doing this cuts the ends of the first and everything else is in range.

+5
source

If this is for an array, you can use numpy.clip .

Otherwise, I think your solution is the best. Or you can define your own function that does the same for a single element if you do it in multiple places.

+4
source

Another option that you can consider more pythonic:

 if x > 100: x = 100 elif x < 1: x = 1 
+2
source

How about something a little different:

 a = (1, x, 100)[-(x<1)+1+(x>100)] 

or if you define your limits as

 lo, hi = (1, 100) a = (lo, x, hi)[-(x<lo)+1+(x>hi)] 

Or change your details and look more elegant:

 a = (x,lo,hi)[(x<lo)-(x>hi)] 

This is possible in python because booleans behave like the values ​​0 and 1, allowing the math inside [] to get the correct tuple index.

+2
source
 a = x if x in range(1,100) else 1 if x < 1 else 100 

Do you really need to fly at 1 and at 100?

-1
source

All Articles