How does 'range()' work internally?
<p>How does the range() differentiate the call being made in this case?</p>

<p><strong>Example:</strong></p>

<pre><code>def ex():
    list = [1,2,3,4]
    for val in range(len(list)):
        print(val)
        break
    for val in range(len(list)):
        print(val)
        break
</code></pre>

<p><strong>Output -</strong> </p>

<pre><code>0
0
</code></pre>

<p>In short, my question is why doesn't the output yield this way?</p>

<pre><code>0
1
</code></pre>

<p>During the first call to the range() in the 'first for loop' , the call is 'range(len(list))',
and in the first call to the range() in the 'second for loop', the call is 'range(len(list))' which the equivalent to the second call to the range() in the 'first for loop'. How does range() know if the call was from 'second for loop' and not 'first for loop'?</p>

<p>I'm not sure why you expect <code>range</code> <em>would</em> remember that it had been called previously. The class does not maintain any state about previous calls; it simply does what you ask. Each call to <code>range(x)</code> returns a new <code>range</code> object that provides numbers from 0 to <code>x-1</code> as you iterate over it. Each call is independent of any previous calls.</p>

<p>To get the behavior you are describing, you need to reuse the <em>same</em> <em>iterator</em> for the <code>range</code> object in each loop.</p>

<pre><code>Python 3.5.1 (default, Apr 18 2016, 11:46:32)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; l = [1,2,3,4]
&gt;&gt;&gt; r = range(len(l))
&gt;&gt;&gt; for val in r:
...   print(val)
...   break
...
0
&gt;&gt;&gt; for val in r:
...   print(val)
...   break
...
0
&gt;&gt;&gt; i = iter(r)
&gt;&gt;&gt; for val in i:
...   print(val)
...   break
...
0
&gt;&gt;&gt; for val in i:
...   print(val)
...   break
...
1
</code></pre>

<hr>

<p>You can image that something like</p>

<pre><code>for x in xs:
    do_something(x)
</code></pre>

<p>is short for</p>

<pre><code>i = iter(xs)
while True:
    try:
        x = next(i)
    except StopIteration:
        break
    do_something(x)
</code></pre>

<p><code>iter</code> returns its argument if it is already, in fact, an iterator, so every <code>for</code> loop returns a fresh, start-at-the-beginning iterator when you attempt to iterate over a non-iterator iterable.</p>

python range