Variable access area for loop

I searched for SO before posting this question here and hopefully this is not duplicated.

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

The output is as follows:

-

I came from the C ++ world and couldn't understand why idx is still in scope when the code is outside the for loop?

thanks

+8
python
source share
1 answer
Cycle

for creates no scope. That's why.

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

From documents :

The blocks are listed below:

  • module
  • function body
  • class definition

Update

Generator expressions have their own areas.

Like Python 3.0 , lists also have their own areas.

+10
source share

All Articles