Why is this legal?

Gary Herron gherron at islandtraining.com
Thu Sep 9 03:21:03 CEST 2004

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
    cluster = [c for (ignored,c) in cluster] # undecorate
    cluster = [item[1] for item in cluster] # undecorate

> 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