for x in... x remains global

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Nov 8 07:23:29 EST 2006


Antoine De Groote <antoine at vo.lu> writes:

> for x in range(3): pass
>
> After this statement is executed x is global variable.

Not exactly. The name 'x' is bound at the scope of the 'for'
statement, and remains bound after the 'for' statement stops, just as
it would be if it was bound in any other statement.

> This seems very unnatural to me and caused me 3 three days of
> debugging because I was unintentionally using x further down in my
> program (typo).

This is, when used intentionally, one of the main useful features of
this behaviour: to determine where an iteration stopped by using the
value bound to the name ('x' in this case) after the iteration
statement.

> I would have thought that variables like this are local to the for
> block.

They're bound at the scope of the 'for' statement. They're available
inside the suite of that statement.

> Is there a reason this is not the case? Maybe there are PEPs or
> something else about the matter that you can point me to?

This message addresses it:

    <URL:http://mail.python.org/pipermail/python-dev/2006-April/064624.html>

A search for the separate terms "python iteration variable scope" will
turn up more.

-- 
 \          "The best way to get information on Usenet is not to ask a |
  `\            question, but to post the wrong information."  -- Aahz |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list