Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.sort() does not return the sorted list [duplicate]

Tags:

python

I'm beginning python and am a little confused about why the following outputs None:

x= [3,1,2]
y = x.sort()
print(y)  # output = None

I was expecting the output to be [1,2,3], but instead I get None. Please note: I am aware of how to get the correct output now but am still curious about what is happening here for the output to be none. In my mind, the second line evaluates x.sort() as [1,2,3], and then this be assigned to variable y.

like image 429
user3880632 Avatar asked Jun 19 '26 05:06

user3880632


1 Answers

The documentation for list tells you that calling the sort method on a list will do an INPLACE sort. I.E it will sort the values inside the current object. Thus it doesnt return any value for you to store in y.

>>> x = [3,1,2]
>>> x.sort()
>>> print(x)
[1, 2, 3]

However you may have a legitimate reason to want to sort the list of X without actually changing it and instead store the sorted output as a new object. You can do this by passing X to sorted function

>>> x = [3,1,2]
>>> y = sorted(x)
>>> print(x, y)
[3, 1, 2] [1, 2, 3]
like image 134
Chris Doyle Avatar answered Jun 25 '26 01:06

Chris Doyle