Run same loop twice, but getting different results
<p>I cannot figure this out, but say I have a depth-3 array of strings called "text".</p>

<p>How can it be that in the following code:</p>

<pre><code>print "FIRST"
for gate in text[1:]:
    print "GATE"
    for text in gate:
        print "TEXT"
        for entry in text:
            print "ENTRY"
            print what

print "SECOND"

for gate in text[1:]:
    print "GATE"
    for text in gate:
        print "TEXT"
        for entry in text:
            print "ENTRY"
            print what
</code></pre>

<p>I get different output for each loop.</p>

<p>"First"</p>

<pre class="lang-none prettyprint-override"><code>FIRST
GATE
TEXT
ENTRY
×

ENTRY
××××¨×ª ××"×£

ENTRY
××× ××××¨ ××©×× ××××××ª, ×××¢××× ×× ××× ××¤× ×©××ª, ××© ××× ×¨××ª ×¤× ×× ××× ××ª××× × ×××©××× ××¡××××ª××, ×× ×× ×××××ª ×¢× ×× × ××©×¨ ×¡×××××ª×× ×××¨×××ª ×¤× ××, ×× ×××× ×××©××ª ××××××ª ×¢× ××©×¨ ××ª×××§×ª ×××¨×× ××× ×¢× ×××©× ×¢×©×¨ ×¤× ××, ×¢× ×× ××© ××× ××©×¨ ××¢× ×× ×××©×× × ××××¨× ×¢××× ××××× ×¢× ×××¨×ª×. ×××© ××× ××©×¨ ××× ×××©××ª ××¢× ×× ×××××¨×ª ××¤×ª×¨×× ××©×× ×¡×××, ××× ××× ×¤×ª×¨×× ×××©×× ××¤×©×¨ ××××× ××¤× ××××§××ª××× ××ª××¦×××ª×××.

TEXT
ENTRY
××.
</code></pre>

<p>"Second"</p>

<pre class="lang-none prettyprint-override"><code>SECOND
GATE
TEXT
ENTRY
×
TEXT
ENTRY
×ª
TEXT
ENTRY
×
TEXT
ENTRY
×
TEXT
ENTRY
</code></pre>

<p>Each Loop is coded exactly the same and yet I get different output. How is this possible?</p>

<p><code>for</code> loops "leak" variables. You might expect <code>gate</code>, <code>text</code>, and <code>entry</code> to be scoped to their respective loops, but they're actually global. So, at the end of this loop</p>

<pre><code>for text in gate:
</code></pre>

<p>The value of <code>text</code> has been altered, which affects the next loop.</p>

<p>Here's a more minimal example:</p>

<pre><code>x = 'abc'   

for x in x:
    print x,
# output: "a b c"

for x in x:
    print x,
# output: "c"
</code></pre>

<p>(If being able to run the same code twice and get the same result is the kind of thing that you find valuable, Python might not be the right choice of language for you. There are plenty of <a href="https://en.wikipedia.org/wiki/Purely_functional_programming">lovely</a> languages that do have this property.)</p>

python