infinite while loop in python when integer compared with range
<p>my while code:</p>

<pre><code>i=0
    a = range(100)
    while i &lt; range(100):
        print i
        i += 9
</code></pre>

<p>this goes into an infinite loop...may i know why?</p>

<p>is it because an integer is compared to the list?
but what happens when i becomes greater than 99?</p>

<p>shouldnt it come out of the while loop?</p>

<p>below code works fine as expected:</p>

<pre><code>i=0
        a = range(100)
        a_len = len(a)
        while i &lt; a_len:
            print i
            i += 9
</code></pre>

<p>Sadly in Python 2.x, an <code>int</code> is always less than a <code>list</code> (even if that list is empty).</p>

<pre><code>&gt;&gt;&gt; 9 &lt; []
True
</code></pre>

<p>What you want to be doing is using the 3-argument form of <code>range</code> so you have a <em>start</em>, a <em>stop</em> and a <em>step</em>, eg:</p>

<pre><code>for i in range(0, 100, 9):
    print i
</code></pre>

python python-2.7 while-loop