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

0

1 Answer 1

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.

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

3 Comments

In fact, only very few language constructs create scopes. There's only module scope, class scope and function scope, and that's about it.
List comprehensions also have their own scopes. Well, any comprehension or generator expression.
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.)

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.