Fix Python – How to clamp an integer to some range?

Question

Asked By – Denilson Sá Maia

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))

Now we will see solution for issue: How to clamp an integer to some range?


Answer

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))

This question is answered By – S.Lott

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0