Question

I'm observing some odd behavior. Here is the snippet of code:

>>> import numpy as np
>>> a = [[1, .3], [0, .5], [2, .23]]
>>> b = np.array(a.sort())
>>> b
array(None, dtype=object)

Is this behavior expected? If I add an intermediate step for the in-place sort, it works as expected:

>>> a = [[1, .3], [0, .5], [2, .23]]
>>> a.sort()
>>> b = np.array(a)
>>> b
array([[ 0.  ,  0.5 ],
       [ 1.  ,  0.3 ],
       [ 2.  ,  0.23]])

Can someone explain what is happening?

Was it helpful?

Solution

The issue is that a.sort() does not return the sorted list. It returns None:

>>> a.sort() is None
True

You could use sorted(a):

>>> b = np.array(sorted(a))
>>> b
array([[ 0.  ,  0.5 ],
       [ 1.  ,  0.3 ],
       [ 2.  ,  0.23]])

However, this would create a (sorted) copy of a.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top