Numpy: Should I use newaxis or None?

In numpy, you can use the newaxis object in the slice syntax to create a length axis of one, for example:

import numpy as np print np.zeros((3,5))[:,np.newaxis,:].shape # shape will be (3,1,5) 

The document states that you can use None instead of newaxis , the effect is exactly the same.

Is there any reason for choosing one over the other? Is there a general approach or style guide? My impression is that newaxis more popular, perhaps because it is more pronounced. So, is there a reason None is allowed?

+72
python numpy
Jun 03 '09 at 13:48
source share
1 answer

None allowed because numpy.newaxis is just an alias for None .

 In [1]: import numpy In [2]: numpy.newaxis is None Out[2]: True 

The authors probably chose this because they needed a convenient constant, and None was available.

Why you should prefer newaxis over None : this is mainly because it is more explicit, and partly because someday numpy authors can change it to something other than None . (They do not plan and probably will not, but there is no good reason to prefer None .)

+83
Jun 03 '09 at 15:05
source share
โ€” -



All Articles