Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access scope of variable in for loop

Tags:

python

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

like image 681
q0987 Avatar asked Oct 10 '11 15:10

q0987


People also ask

What is the scope of variable in for loop?

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.

What is the scope of a for loop in Python?

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.

Can you access a variable outside of a for loop?

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.

Can you use variables in a for loop?

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.


1 Answers

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.

like image 156
ovgolovin Avatar answered Sep 28 '22 07:09

ovgolovin