sorted or .sort() ?

Raymond Hettinger python at rcn.com
Mon Jun 16 13:38:59 EDT 2008


On Jun 16, 5:11 am, Peter Bengtsson <pete... at gmail.com> wrote:
> 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.
>
> 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)?

Here's how sorted() works:

def sorted(iterable, *args, **kwds):
    s = list(iterable)
    s.sort(*args, **kwds)
    return s

So, sorted() runs at the same speed as list.sort() except for the step
where the input gets copied.  For list inputs, that extra time is
trivial compared to the cost of actually doing the sort.  I wouldn't
worry about the negligible performance difference.  Use whichever fits
best in your program.

Raymond



More information about the Python-list mailing list