unintuitive for-loop behavior

Steve D'Aprano steve+python at pearwood.info
Fri Sep 30 14:38:23 EDT 2016


On Fri, 30 Sep 2016 11:43 pm, BartC wrote:

> It can make sense for 'x' to be local to this for-loop block (everything
> else is at it works now), and independent of any x's in outer blocks. It
> means being able to do stuff like this:
> 
>     for x in a:
>       for x in b:
>          pass
>       pass     # outer x still has its value

If you're (generic you) not using the loop variables, as in your example,
why do you care if one overwrites the other? You're not using either of
them.

And if you are using them, then surely you need them to be different names
so you can use them *both*. So why does it matter if they are in different
scopes?

I can't think of an example of where I would want two nested for-loops,
where *both* loop variables need to be the same name, but I only want to
access the inner variable inside the inner loop and the outer variable in
the outer loop.

And if I was in that position, why couldn't I just relax the "must be the
same name" condition and give them different names? Its not like there is a
shortage of possible names.


> And any even more outer x's are not affected. With 'for', especially one
> inside a list-comp, often you just need some throwaway index variable
> without worrying if it will clash with an existing local.
> 
> But it's not useful enough I think to bother changing now. Or even when
> the language was designed.

Indeed.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list