8

I have searched the SO before I post this question here and hopefully this is not a duplicated one.

def print_me():
    a_list = range(1, 10)
    for idx, aa in enumerate(a_list):
        pass
    print(idx)

if __name__ == '__main__' : print_me()

Output is as follows:

8

I came from C++ world and could not figure out why idx is still in the scope when the code is out side of for loop?

Thank you

q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

10

for loop doesn't create any scope. This is the reason.

In this particular code idx is a local variable of the print_me function.

From the docs:

The following are blocks:

  • a module
  • a function body
  • a class definition

Update

Generator expressions have their own scopes too.

As of Python 3.0 list comprehensions also have their own scopes.

Community
  • 1
  • 1
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
  • 2
    In fact, only very few language constructs create scopes. There's only module scope, class scope and function scope, and that's about it. –  Oct 10 '11 at 15:50
  • List comprehensions also have their own scopes. Well, any comprehension or generator expression. – kindall Oct 10 '11 at 16:37
  • 2
    Anyone knows *why* Python doesn't create a scope for `for` / `while` loops? Is there any benefit to having those variables present later? (The disadvantage is clearly namespace pollution, hence more bugs.) – max Nov 21 '12 at 03:43