Why is this legal?

Michael George Lerner mlerner at asteroids.gpcc.itd.umich.edu
Wed Sep 8 23:34:44 EDT 2004


Gary Herron <gherron at islandtraining.com> wrote:
> On Wednesday 08 September 2004 02:05 pm, Michael George Lerner wrote:
>> I tracked down a bug today that boiled down the "undecorate" part of
>> this "decorate-sort-undecorate":
>>
>>     cluster = [(c.resi,c) for c in cluster] # decorate
>>     cluster.sort()                          # sort
>>     cluster = [c for (c.resi,c) in cluster] # undecorate
>>
>> That last line actually assigns c.resi for each c in cluster.

> So if you don't want to assign to c.resi don't use it as a loop
> variable:
>     cluster = [c for (ignored,c) in cluster] # undecorate
> or
>     cluster = [item[1] for item in cluster] # undecorate

Yup.  I rewrote it as
    cluster = [c for (resi,c) in cluster] # undecorate
once I found the bug.

I think I was just annoyed that it was so easy to write the
undecorate line by copying the decorate line and moving terms
around .. easy, but broken.

You and Jeff Shannon have convinced me that I just need to make
sure that I don't forget that a list comprehension is really
just a cute for loop.

It still seems a little jarring, though.

Thanks,

-michael

>> Is there any reason you'd ever want to do this?

> There is a big reason to want it to stay this way.  The rule that
> "each pass through the loop rebinds the loop variable (or tuple of
> loop variables)" is simple, and clear.  For that reason alone, we
> don't want to ever change it.

> Gary Herron





More information about the Python-list mailing list