Why is this legal?

Gary Herron gherron at islandtraining.com
Wed Sep 8 21:21:03 EDT 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
variable:
    cluster = [c for (ignored,c) in cluster] # undecorate
or
    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