sorted or .sort() ?
Nick Craig-Wood
nick at craig-wood.com
Mon Jun 16 17:31:29 EDT 2008
Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> Peter Bengtsson <peterbe at gmail.com> writes:
>
> > My poor understanding is that the difference between `sorted(somelist,
> > key=lambda x:...)` and `somelist.sort(lambda x,y...)` is that one
> > returns a new list and the other sorts in-place.
>
> Yes.
>
> > Does that mean that .sort() is more efficient and should be favored
> > when you can (i.e. when you don't mind changing the listish object)?
>
> No, it means you should choose the version that expresses what you
> actually want to do.
>
> Efficiency of the programmers ??? including the unknown number of
> programmers who will have to read the code after you write it ??? is in
> many cases a much more important criterion than efficiency of the CPU.
> People's time continues to be much more expensive than computer time,
> after all.
Good advice with one caveat: sorted() was only introduced in python
2.4 so if your code must run on earlier versions then use list.sort()
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list