+ 1
Why I am getting no result while sorting the lists?
In the first case code gives 'none' as an output but in second it works. Please explain the difference? https://code.sololearn.com/ccYMWkP4XA7T/?ref=app
5 odpowiedzi
+ 5
Aman Kumar
sort() does an inplace sort on the iterable that it is called from and doesn't return a new list from the method, so, None is returned by default.
If you passed the list to the sorted() function you would get the output you expected from the 1st as it will make a copy of the list, then sort and return the sorted copy from the function.
print(sorted(x))
run this code to see the difference between the 2
x = ["potter", "harry"] # unsorted list
print(sorted(x)) # returns sorted copy of x
print(x) # x is unchanged
x.sort() # inplace sort of x
print(x) # x is now changed
+ 1
# this code gives 'none'as an output
x = ["harry","potter"]
x.sort()
print(x)
# in this case the code works efficiently
y = ["apple","banana"]
y.sort()
print(y)
#do like this
+ 1
Because you have to print the sorted list which you will get after .sort() method
+ 1
But why I am getting none
why I didn't get the original list
+ 1
Because at that point only sorting is taking place