Newbie Question: Sort Tip: Why n=n?

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Fri Jan 18 01:15:40 EST 2002


On Fri, 18 Jan 2002 00:49:46 -0500, Joshua Muskovitz <joshm at taconic.net> wrote:
>> 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?
>
>Because the lambda function does not have access to 'n' directly.  So it
>declares a local 'n' that is set once at compile time to refer to the actual
>n.  (Essentially it caches the value of 'n'.)

In addition to simulating lexical scope, it's also an optimization trick,
because you can load locals faster than globals.



More information about the Python-list mailing list