How can I clamp (clip, restrict) a number to some range?

clamp, python

Solution

This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.

new_index = max(0, min(new_index, len(mylist)-1))

Problem

I have the following code: ``` new_index = index + offset if new_index < 0: new_index = 0 if new_index >= len(mylist): new_index = len(mylist) - 1 return mylist[new_index] ``` Basically, I calculate a new index and use that to find some element from a list. In order to make sure the index is inside the bounds of the list, I needed to write those 2 `if` statements spread into 4 lines. That's quite verbose, a bit ugly... Dare I say, it's quite un-pythonic. Is there any other simpler and more compact solution? (and more pythonic) Yes, i know I can use `if else` in one line, but it is not readable: ``` new_index = 0 if new_index < 0 else len(mylist) - 1 if new_index >= len(mylist) else new_index ``` I also know I can chain `max()` and `min()` together. It's more compact, but I feel it's kinda obscure, more difficult to find bugs if I type it wrong. In other words, I don't find it very straightforward. ``` new_index = max(0, min(new_index, len(mylist)-1)) ``` See Pythonic way to replace list values with upper and lower bound (clamping, clipping, thresholding)? for specific technique to process values in a Numpy array.

Original source

Related problems