Home>

Eliminate the arr.sort (1) line in the code below,
If i suddenly write print (arr.sort (1)), None will be output.
Please tell me why you should write arr.sort (1).

import numpy as np
arr = np.array ([[8, 4, 2], [3, 5, 1]])
arr.sort (1)
print (arr)
  • Answer # 1

    The

    arr.sort (1)method has no return value.

    arr.sort ()prioritizes memory efficiency and processing speed by performing destructive sorting

    As a Python policy, methods that make destructive changes have no return value

    Reference

    Why doesn't list.sort () return a sorted list? -Design and History FAQ — Python 3.7.5 documentation

  • Answer # 2

    The code calls thesortmethod of thenumpy.ndarrayobject. As you can see from the reference,

      

    Sort an array in-place. Refer to numpy.sort for full documentation.

      

    numpy.ndarray.sort — NumPy v1.17 Manual

    It is described as

    and there is no description of the return value. No return value means that in Python, it returns aNoneobject.

    In short, it is a "specification". A general trend of Python built-in functions and objects, library functions and methods is that "methods that change objects themselves in-place" returnNone(this is called Command I'm influenced by the idea of ​​the/Query separation principle.

    Not only

    numpyarrays but also built-inlisthas the same specifications, andlist.sortsortedfunction that returns a new sortedlistobject.