Why is this legal?

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu Sep 9 00:47:54 EDT 2004


Michael George Lerner write:

>     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.

Normally the best way to write the above is:

     cluster = [(c.resi,c) for c in cluster] # decorate
     cluster.sort()                          # sort
     cluster = [c[-1] for c in cluster]      # undecorate

It's shorter, clearer, works no matter how many elements are in the
decoration, and doesn't have the danger of your version.

Tim Delaney



More information about the Python-list mailing list