I am totally confused on the below code execution,
a= [10,30,4]
a = a.sort()
r = len(a) - 1
print (r)
When the above code is executed I get
r = len(a) - 1
TypeError: object of type 'NoneType' has no len()
However the code runs fine if I find the length without sorting or when sorting the array after find the length. Is there any reason to this?
a.sort()
is an inplace operation. It modify list inplace and does not return anything. See the documentation for list.sort
by typing help(list.sort)
in your python interpreter.
>>> help([].sort) Help on built-in function sort: sort(*, key=None, reverse=False) method of builtins.list instance Sort the list in ascending order and return None. The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained).
So the point is, you should not assign the return value of listobject.sort()
because it will always return None