Getting error when trying to calculate the length of the array after sort in python

Viewed 110

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?

3 Answers

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

The value returned by a function sort is None

So when you are trying to assign a = a.sort() it is the same as a = None

Here is the reference to sorting basics

Your code should look like

a= [10,30,4]
a.sort()
r = len(a) - 1
print (r)

In addition to the other answers, if you want a non-inplace function then you can run:

a = sorted(a)

Related