Ester Lin
Ester Lin

Reputation: 617

Run same loop twice, but getting different results

I cannot figure this out, but say I have a depth-3 array of strings called "text".

How can it be that in the following 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

I get different output for each loop.

"First"

FIRST
GATE
TEXT
ENTRY
א

ENTRY
מחברת אל"ף

ENTRY
אחל לבאר לשון יהודית, להעמיד כל מלה כפי שאת, יש מלה רבת פנים ולא יתבונן המשכיל יסודותיה, כי אם במהות ענינה אשר סביבותיה למרבית פניה, כי המלה מושכת והולכת עד אשר מתחלקת ממראה אחד עד חמשה עשר פנים, על כן יש מלה אשר הענין ימשכנה ויורה עליה וילמד על גזרתה. ויש מלה אשר היא מושכת הענין ומבארת הפתרון ושכל סודו, וכה הוא פתרון הלשון ופשר המלים לפי מחלקותיהם ותוצאותיהם.

TEXT
ENTRY
אב.

"Second"

SECOND
GATE
TEXT
ENTRY
מ
TEXT
ENTRY
ת
TEXT
ENTRY
ח
TEXT
ENTRY
ל
TEXT
ENTRY

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

Upvotes: 1

Views: 1198

Answers (2)

Chris Martin
Chris Martin

Reputation: 30756

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

for text in gate:

The value of text has been altered, which affects the next loop.

Here's a more minimal example:

x = 'abc'   

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

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

(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 lovely languages that do have this property.)

Upvotes: 6

Moses Koledoye
Moses Koledoye

Reputation: 78554

text has been modified. Before the SECOND loop, text has its value taken from the last iteration of for text in gate: ...

You should consider renaming the inner loop variable to something different.

Upvotes: 6

Related Questions