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

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Thu Sep 16 17:41:37 CEST 2010


On Thu, 16 Sep 2010 10:35:14 -0500
Daniel Stutzbach <daniel at stutzbachenterprises.com> 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')

-1

I think the idiom using the operator module tools:

mylist.sort(key=itemgetter(1))
mylist.sort(key=attrgetter('length'))

is more readable than your proposal - it makes what's going on
explicit.

	<mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list