Newbie Question: Sort Tip: Why n=n?

Joshua Muskovitz joshm at taconic.net
Fri Jan 18 00:49:46 EST 2002


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

--
# Joshua Muskovitz
# joshm at taconic.net
def lyyrs(sig): return '-'.join(sig.split()+["ly y'rs"])
lyyrs('Hire me!  I need the work!')




-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----



More information about the Python-list mailing list