title: `in range` construction in python 2 --- working too slow
body: <p>I wanted to check if a given <code>x</code> lies in the interval <code>[0,a-1]</code>.
  As a lazy coder I wrote 
  </p>
  
  <pre><code>x in range(a)
  </code></pre>
  
  <p>and (because that piece of code was in 4.5 nested loops) quickly run into performance issues. I tested it and indeed, it turns out runtime of <code>n in range(n)</code> lies in O(n), give or take. I actually thought my code would be optimized to <code>x &gt;= 0 and x &lt; a</code> but it seems this is not the case. Even if I fix the <code>range(a)</code> in advance the time doesn't become constant (though it improves a lot) - see side notes.</p>
  
  <h2>So, my question is:</h2>
  
  <p>Should I use <code>x &gt;= 0 and x &lt; a</code> and <strong>never</strong> write <code>x in range(a)</code> ever again? Is there an even better way of writing it?</p>
  
  <hr>
  
  <p>Side notes:</p>
  
  <ol>
  <li>I tried searching SO for <a href="https://stackoverflow.com/questions/tagged/range+python-2.7+performance">range, python-2.7, performance</a> tags put together, found nothing (same with <a href="https://stackoverflow.com/questions/tagged/range+python-2.x+performance">python-2.x</a>).</li>
  <li><p>If I try following:</p>
  
  <pre><code>i = range(a)
  ...
  x in i
  </code></pre>
  
  <p>so that the range is fixed and I only measure runtime of <code>x in i</code>, I still get runtime in O(x) (assuming <code>a</code> is large enough).</p></li>
  <li>runtime of <code>n in xrange(n)</code> lies in O(n) as well.</li>
  <li>I found <a href="https://stackoverflow.com/q/30081275/9297127">this post</a>, which asks similar question for python 3. I decided to test same stuff on python 3 and it rolled through tests like it's nothing. I got sad for python 2.</li>
  </ol>