Home > Mobile >  Changing the chain order of the methods in NumPy is giving None and different output
Changing the chain order of the methods in NumPy is giving None and different output

Time:10-18

I ran the following code related to Numpy arrays.

import numpy as np

a = np.array([[1,4],[3,1]])

np_array = np.sort(a.flatten())
print(np_array)

np_array2 = a.flatten().sort()
print(np_array2)

I got the following output.

[1 1 3 4]
None

I expected this output.

[1 1 3 4]
[1 1 3 4]

Why is this difference in the output? What concept of programming is this?

CodePudding user response:

You get none because .sort() operates differently from sorted() or np.sort(). The *.sort() is in place (ie. the original list) whereas the other methods both create a new list.

So this is an example that works (the way you want it):

import numpy as np

a = np.array([[1,4],[3,1]])

np_array = np.sort(a.flatten())
print('nparraay', np_array)

np_array2 = a.flatten()
print('nparraay2 (part 1):', np_array2)

np_array2 = np.sort(np_array2)
print('nparraay2 (part 2):', np_array2)

result:

nparraay [1 1 3 4]
nparraay2 (part 1): [1 4 3 1]
nparraay2 (part 2): [1 1 3 4]
  • Related