3

I was trying to run some code and sort an array, below is the code. Online it says that an array can be sorted using this way but when I run this code, the output is None instead of the sorted code, can someone explain why? In Jupyter Notebook it works fine when I tested it. Both ways don't work - why is that ?

import numpy as np
arr = np.array([3, 7, 6, 8, 9, 1, 2, 3])
arr_sorted = arr.sort()
print(arr_sorted)

# alternative way 
arr_sorted2 = np.ndarray.sort(arr)
    print(arr_sorted2)

Additionally I found that this works instead - but I still don't know the why.

print(np.sort(arr))
ab = np.sort(arr)
print(ab)

enter image description here

2 Answers 2

6

The reason is when you call sort() on the array itself, it sorts the array in-place and returns None, so arr_sorted is None too in the first part of your code. Better call the method ins this way:

arr.sort()

This is also the case for np.ndarray.sort(arr), therefore arr_sorted2 is also None.

But, calling np.sort(arr) returns the sorted array as another object, and it should be called in this way:

arr = np.sort(arr)

The behavior is the same for Jupyter, you may need to restart your notebook and try again to get valid outputs from your code, because the notebook might held the last state of your variables.

Sign up to request clarification or add additional context in comments.

Comments

0

If you take sort as the method of class ndarray, it sorts the array in place and returns None, but if you use sort like a funcion of numpy by calling np.sort, then in this case it returns a sorted copy of the array, and the original reamins the same. So it is not a malfunction of numpy in Pycharm

3 Comments

why does it work though in jupyter then?
it also outputs None in Jupyter
check the picture i have added on top please @Berger - ah now i see! thanks both

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.