0
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
Ted
  • 469
  • 4
  • 16
  • duplicate of [Scoping in Python 'for' loops](https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops) –  May 29 '18 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. – Ctrl S May 29 '18 at 18:15
  • Yes, Python doesn't work like Java/C. You can find a simple explanation of these rules [here](https://docs.python.org/3/reference/executionmodel.html#naming-and-binding). 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. – juanpa.arrivillaga May 29 '18 at 18:21

1 Answers1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681