The first of these 2 lines is useless. python does not require that you initialize or 'pre-define' a variable. The first creates an array; the second also creates one, and reassigns the variable. The original value of new_array is discarded.
new_array = np.ndarray(5, dtype=np.int32)
...
new_array = array[perm]
And as a general rule, np.ndarray is only used for advanced purposes. np.array, np.zeros etc are used to create new arrays.
array is a poor choice of variable name. array looks too much like np.array, and actually confused me when I first copied the above lines.
array = np.array([10,20,30,40,50])
In sum your code does:
In [28]: arr = np.array([10,20,30,40,50])
In [29]: perm = np.random.permutation(arr.shape[0])
In [30]: perm
Out[30]: array([2, 0, 1, 4, 3])
In [31]: arr1 = arr[perm]
In [32]: arr1
Out[32]: array([30, 10, 20, 50, 40])
arr1 is a new array with values selected from arr. arr itself is unchanged.
You could assign values to predefined array this way:
In [35]: arr2 = np.zeros(5, int)
In [36]: arr2
Out[36]: array([0, 0, 0, 0, 0])
In [37]: arr2[:] = arr[perm]
In [38]: arr2
Out[38]: array([30, 10, 20, 50, 40])
In arr[perm], the result is the same shape as perm, in this case a 5 element 1d array. If I turn perm into a (5,1) column array, the result is also a (5,1) array:
In [40]: arr[perm[:,None]]
Out[40]:
array([[30],
[10],
[20],
[50],
[40]])
In [41]: _.shape
Out[41]: (5, 1)
Another example of array indexing - with a (2,2) array:
In [43]: arr[np.array([[0,1],[2,3]])]
Out[43]:
array([[10, 20],
[30, 40]])
new_array = array[[3,2,0,1]]wouldn't initialize a new (perhaps 2D) array with the elements of inner array (as the first row)?[]with(), the former is for indexing, and the latter is for constructing new arrays.np.ndarrayclass to construct arrays. Usenp.array,np.empty, etc. where possible.