+ 2

Python - Why a is None?

l = [1,9,65,88,4,0] a = l.sort() b = sorted(l) print(a) print(b) I expect, since it is assigned to a variable, sorted array is stored in a!

16th Sep 2019, 2:05 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
2 Answers
+ 6
It is because the sort() method of a list only modifies the value of the list object while not returning any value, therefore returning the default value None that is returned by functions not explicitly returning anything. So here is how it works: a=[1, 5, 4, 4] val=a.sort() #a now becomes [1, 4, 4, 5] #function returns nothing, so val is None print(val) #prints None
16th Sep 2019, 2:11 PM
👑 Prometheus 🇾🇬
👑 Prometheus 🇾🇬 - avatar
+ 4
list.sort is an in-place-method. It sorts the list and that was it. And in Python, everything that doesn't return anything, returns None. b on the other hand returns a sorted copy.
16th Sep 2019, 2:13 PM
HonFu
HonFu - avatar