Sort a part of a list in place

Headcrab picture Headcrab · Feb 16, 2010 · Viewed 42.8k times · Source

Let's say we have a list:

a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]

Now, a.sort() will sort the list in place. What if we want to sort only a part of the list, still in place? In C++ we could write:

int array = { 4, 8, 1, 7, 3, 0, 5, 2, 6, 9 };
int * ptr = array;
std::sort( ptr + 1, ptr + 4 );

Is there a similar way in Python?

Answer

fviktor picture fviktor · Feb 16, 2010

I'd write it this way:

a[i:j] = sorted(a[i:j])

It is not in-place sort either, but fast enough for relatively small segments.

Please note, that Python copies only object references, so the speed penalty won't be that huge compared to a real in-place sort as one would expect.