Oddity using sorted with key

John Gordon gordon at panix.com
Tue Mar 11 17:25:29 CET 2014


In <058a4a9e-7893-44ef-97c0-999a3589e82a at googlegroups.com> Josh English <Joshua.R.English at gmail.com> writes:

> print list(sorted(all_the_stuff, key=lambda x: x.name.lower))
> print list(sorted(all_the_stuff, key=lambda x: x.name.lower()))

> # END

> The output is:

> [Thing d, Thing f, Thing 2, Thing a, Thing b, Thing C]
> [Thing 2, Thing a, Thing b, Thing C, Thing d, Thing f]

> Any ideas why I'm seeing two different results? Especially as the correct
> form is giving me the wrong results?

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.

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list