In numpy one can use the ‘newaxis’ object in the slicing syntax to create an axis of length one, e.g.:
import numpy as np
print np.zeros((3,5))[:,np.newaxis,:].shape
# shape will be (3,1,5)
The documentation states that one can also use None instead of newaxis, the effect is exactly the same.
Is there any reason to choose one over the other? Is there any general preference or style guide? My impression is that newaxis is more popular, probably because it is more explicit. So is there any reason why None is allowed?
Noneis allowed becausenumpy.newaxisis merely an alias forNone.The authors probably chose it because they needed a convenient constant, and
Nonewas available.As for why you should prefer
newaxisoverNone: mainly it’s because it’s more explicit, and partly because someday thenumpyauthors might change it to something other thanNone. (They’re not planning to, and probably won’t, but there’s no good reason to preferNone.)