Newbie Question: Sort Tip: Why n=n?

Tim Roberts timr at probo.com
Fri Jan 18 00:37:44 EST 2002


vaughn at sewardSBLOKconsulting.comMAND.invalid (Vaughn H. Seward) wrote:

>In "Python Performance Tips", Guido van Rossum has a little tip on
>sorting:
>
>http://manatee.mojam.com/~skip/python/fastpython.html#sorting
> 
>He suggests the following:
> 
>def sortby(list, n):    
>    nlist = map(lambda x, n=n: (x[n], x), list)
>    nlist.sort()    
>    return map(lambda (key, x): x, nlist)
> 
>I understand everything about this except the n=n in the second line.
>Does anyone know why this is required?

Actually, this is no longer required in Python 2.2.

In earlier Pythons, embedded functions did not have access to the local
variables in outer function: just globals and their own locals.  The "n=n"
is a trick to pass the outer value of "n" into the inner function's local
namespace.  The "n" inside the lambda function refers to the lambda's local
copy of "n", not sortby's copy of "n".

In Python 2.2, namespaces are nested, so that the lambda function has
direct access to sortby's "n".  In Python 2.1, you can get the same
behavior by adding the following line at the very beginning:

  from __future__ import nested_scopes
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list