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
The variable is within the scope of the loop. I.e. you need to be within the loop to access it. It's the same as if you declared a variable within a function, only things in the function have access to it.
In Python, for-loops use the scope they exist in and leave their defined loop-variable behind in the surrounding scope. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.
If the variable is declared outside the loop, then it has the global scope as it can be used through-out the function and inside of the loop too. If the variable is declared inside the loop, then the scope is only valid inside the loop and if used outside the loop will give an error.
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
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:
Update
Generator expressions have their own scopes too.
As of Python 3.0 list comprehensions also have their own scopes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With