Oddity using sorted with key

Josh English Joshua.R.English at gmail.com
Tue Mar 11 18:02:16 CET 2014


On Tuesday, March 11, 2014 9:25:29 AM UTC-7, John Gordon wrote:
> 
> 
> 
> 
> Why do you say that 'key=lambda x: x.name.lower' is the correct form? That
> 
> returns the str.lower() function object, which is a silly thing to sort
> 
> on.  Surely you want to sort on the *result* of that function, which is
> 
> what your second print does.
> 


>From http://docs.python.org/2/library/functions.html:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

And from https://wiki.python.org/moin/HowTo/Sorting/:

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

...

Of course, now that I re-read that, I was mistaking the lambda function with the definition of the lambda function. Stupid me.




More information about the Python-list mailing list