How to clamp an integer to some range? (in Python)
<p>I have the following code:</p>

<pre><code>new_index = index + offset
if new_index &lt; 0:
    new_index = 0
if new_index &gt;= len(mylist):
    new_index = len(mylist) - 1
return mylist[new_index]
</code></pre>

<p>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 <code>if</code> statements spread into 4 lines. That's quite verbose, a bit ugly... Dare I say, it's quite <em>un-pythonic</em>.</p>

<p><strong>Is there any other simpler and more compact solution?</strong> (and more <em>pythonic</em>)</p>

<p>Yes, i know I can use <code>if else</code> in one line, but it is not readable:</p>

<pre><code>new_index = 0 if new_index &lt; 0 else len(mylist) - 1 if new_index &gt;= len(mylist) else new_index
</code></pre>

<p>I also know I can chain <code>max()</code> and <code>min()</code> 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.</p>

<pre><code>new_index = max(0, min(new_index, len(mylist)-1))
</code></pre>
