[Python-ideas] list.sort with a int or str key

Robert Kern robert.kern at gmail.com
Thu Sep 16 17:51:55 CEST 2010

On 9/16/10 10:35 AM, Daniel Stutzbach wrote:
> list.sort, sorted, and similar methods currently have a "key" argument that
> accepts a callable.  Often, that leads to code looking like this:
> mylist.sort(key=lambda x: x[1])
> myotherlist.sort(key=lambda x: x.length)
> I would like to propose that the "key" parameter be generalized to accept str
> and int types, so the above code could be rewritten as follows:
> mylist.sort(key=1)
> myotherlist.sort(key='length')
> I find the latter to be much more readable.  As a bonus, performance for those
> cases would also improve.

I find the latter significantly less readable because they are special cases 
that I need to remember. Right now, you can achieve the performance and arguably 
better readability using operator.itemgetter() and operator.attrgetter():

   from operator import attrgetter, itemgetter


Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-ideas mailing list