1
def temp():
    temparray = ['a','b']
    temparray_2 = ['c','d','e']
    for i in temparray:
        print('i:' + str(i))
        for i in temparray_2:
            print('first: ' + str(i))
        print('Second: ' + str(i))

    print('final: ' + str(i))

Why does the above code the following output? The variable i seems to get overwritten by whatever that is last assigned in the inner loop. Does python not obey the scoping rule like Java or C?

i:a
first: c
first: d
first: e
Second: e
i:b
first: c
first: d
first: e
Second: e
final: e
3
  • duplicate of Scoping in Python 'for' loops Commented May 29, 2018 at 18:06
  • I would avoid using the same variable in nested for statements. If you want one to influence the other, use an assignment. Commented May 29, 2018 at 18:15
  • Yes, Python doesn't work like Java/C. You can find a simple explanation of these rules here. The important bit: "Each assignment or import statement occurs within a block defined by a class or function definition or at the module level (the top-level code block)." Note, that only function definitions, class definitions, and the module create a block with their own scope. Nothing else does. Not for-loops, or if-statements etc. Commented May 29, 2018 at 18:21

1 Answer 1

3

Like any function-local assignment, the loop index is in scope for the entire function the for loop appears in. A for loop itself does not create a new scope.

Sign up to request clarification or add additional context in comments.

4 Comments

Also, a for statement represents an assignment operation.
@MadPhysicist That's what I mean to infer, but I don't think I could have been less explicit :)
infer->imply? :)
I'm going to stop typing now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.