Can not do in place sort and assigned to a variable in python

Question:

I have one basic Question in python:
I want to sort a list and assigned to variable using list.sort(). It does not seem to work why?

Q2 = [0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25]
Q3 = Q2.sort()
Q3 # prints nothing

I wonder why it is so though the Q2 get sorted already if I print Q2
Thanks.

Asked By: juggernaut

||

Answers:

sort is in-place and does not return anything. You’d have to use sorted which sorts and returns a copy of the sorted list, but will leave Q2 unmodified.

>>> Q3 = sorted(Q2)
>>> Q3
[0, 0, 1, 1, 2, 3, 4, 4, 5, 9, 16, 25]

sort is just meant to be called to sort the list without having to make a copy

>>> Q2.sort()
>>> Q2
[0, 0, 1, 1, 2, 3, 4, 4, 5, 9, 16, 25]
Answered By: Cory Kramer

If you really insist on it to be in place you could do this:

Q3 = "lolz" if Q2.sort() else Q2

But I don’t see the point of it 🙂

you should be using sorted(Q2) which returns a sorted list.

Answered By: Reut Sharabani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.