+ 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?
9 Réponses
+ 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
+ 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
+ 7
sure thing 👍
+ 6
@Burey
Thank you, for the explaination!👌
+ 3
It has to do with the return Datatype of the function, whether it is an object or a list.
+ 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).
0
so...
whats the use of...
list.sort()
it returns none...
how and when we use it then????
0
burey
..plz tell me...the use...
- 1
hmm