How can I get a sorted copy of a list?

list, python, sorting

Solution

The following will make a sorted copy of `L` and assign it to `K`:

K = sorted(L)

`sorted()` is a builtin function.

The reason `K = L.sort()` doesn't work is that `sort()` sorts the list in place, and returns `None`. This is why `L` ends up being modified and `K` ends up being `None`.

Here is how you could use `sort()`:

K = L[:] # make a copy
K.sort()

Problem

I have a list `L = [2,0,4,5]`. How can I make a new list that is a sorted version of `L`, without changing `L`? I tried `K = L.sort()`, but then `print(K)` prints `None`, and `L` becomes `[0,2,4,5]`.

Original source

Related problems