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].
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].
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()