+ 1

Why this!?

I wrote: nums= [3,5,2,1,4] nums.sort() output: [1,2,3,4,5] but nums= [3,5,2,1,4] print(nums.sort()) output: None Why it gives none and not an error?

13th Jun 2020, 7:13 PM
Rahi S
Rahi S - avatar
7 Respostas
+ 7
The nums.sort() method sorts the object (the thing before the dot, here nums) as it's first argument and returns None. The built in function sorted(nums) returns a sorted version of nums, so print(sorted(nums)) will display that sorted list. Both the sort() method and the sorted() function also have the 'key' parameter that allows you to sort by an element's index. This example sorts a list of words by the second letter of each word: words = ["Hi", "there"] print(sorted(words, key=lambda word: word[1])) # outputs ["there", "Hi"] words.sort(key=lambda word: word[1]) print(words) # also outputs ["there", "Hi"] See https://docs.python.org/3.9/howto/sorting.html and also https://docs.python.org/3.9/tutorial/classes.html#method-objects An analogous pair is the reverse() method and the reversed() function.
14th Jun 2020, 8:09 AM
David Ashton
David Ashton - avatar
+ 4
Nothing much more to elaborate, really :) If you use the .sort() method on a list, it sorts it in-place, physically change its elements' order. It's job is then done, so it doesn't really need to return anything. So it returns nothing. "Nothing" in Python is None.
13th Jun 2020, 7:25 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
Every function or method in Python has a return value. It can be anything, depending on what the function does: True, False, some string, a tuple, a number... For example if you use the builtin max function, it will return the largest item from the iterable you passed as an argument. Now for some functions/methods, it doesn't make sense to return anything. They're just supposed to do a job - and that was it. Sort is such a method. You ask it to sort a list, and the method does it for you, and that's it. In Python, every function that doesn't return anything, returns the None object instead, which just stands for 'nothing'. It's a placeholder, basically. So it has no sense to do anything with the return value of sort. The method just sorts the list, and then it's over. So you first sort... nums.sort() And now if you want to see the sorted list, you can print it: print(nums)
13th Jun 2020, 8:43 PM
HonFu
HonFu - avatar
+ 1
For Honfu: Great explanation I now fully understand why its giving None Thank ya
14th Jun 2020, 9:32 AM
Rahi S
Rahi S - avatar
0
.sort() method changes the argument, but returns None. That's why :)
13th Jun 2020, 7:16 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
Can you please elaborate
13th Jun 2020, 7:17 PM
Rahi S
Rahi S - avatar
0
if a function does not return any thing like "list.sort()" printing it will show "None"
13th Jun 2020, 8:39 PM
Sousou
Sousou - avatar