13

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user1817310
  • 195
  • 1
  • 1
  • 5

2 Answers2

22

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()
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

You need to use the builtin function sorted: sorted(L)

Praveen Gollakota
  • 37,112
  • 11
  • 62
  • 61