list sort vs sorted list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

list sort vs sorted list

Hey, guys! Found out anouther one tricky stuff in quiz lib and in python indeed. Look at the following code: lst = [34,67,45] print(lst.sort()==sorted(lst)) Right answer is surprisingly False! Surprisingly because if put inplace sort operation before comparision like here: lst = [34,67,45] lst.sort() print(lst==sorted(lst)) https://code.sololearn.com/crzl8w9LBbBd the output is True! Does anybode know how it is working? Why lst.sort()==sorted(lst) is False actually?

9th Sep 2017, 12:47 PM
Alexander Lebedev
Alexander Lebedev - avatar
9 Answers
+ 15
sort changes the original list by sortsing it but does NOT return a new list sorted does not change the original list but returns a new sorted list basically what it translated to is None==sorted(lst) as sort does not returns anything just try this: print(lst.sort()) print(sorted(lst)) and post your results here
9th Sep 2017, 12:52 PM
Burey
Burey - avatar
+ 10
@sayan chandra list.sort() works by changing the list object so no need for it to return anything same way as if you declare a function that does not return anything and print its output def foo(): x = 1 print(foo()) # outputs None
9th Sep 2017, 2:44 PM
Burey
Burey - avatar
+ 7
sure thing 👍
9th Sep 2017, 2:41 PM
Burey
Burey - avatar
+ 6
@Burey Thank you, for the explaination!👌
9th Sep 2017, 12:58 PM
Manual
Manual - avatar
+ 3
It has to do with the return Datatype of the function, whether it is an object or a list.
9th Sep 2017, 1:20 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
Burey, thank you for your help! And you asked :) None [34, 45, 67] I just forgot that inplace method 'sort' actually returns nothing (None).
9th Sep 2017, 1:28 PM
Alexander Lebedev
Alexander Lebedev - avatar
0
so... whats the use of... list.sort() it returns none... how and when we use it then????
9th Sep 2017, 2:39 PM
sayan chandra
sayan chandra - avatar
0
burey ..plz tell me...the use...
9th Sep 2017, 2:42 PM
sayan chandra
sayan chandra - avatar
- 1
hmm
9th Sep 2017, 2:47 PM
sayan chandra
sayan chandra - avatar