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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With