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
forloop doesn’t create any scope. This is the reason.In this particular code
idxis a local variable of theprint_mefunction.From the docs:
The following are blocks:
Update
Generator expressions have their own scopes too.
As of Python 3.0 list comprehensions also have their own scopes.