2

I was writing a line of code and I get some strange output of it.

a = np.arange(2,11).resize((3,3))
print(a)

a = np.arange(2,11).reshape((3,3)) 
print(a)

the first one gives me None but the second one gives me a 3X3 matrix. but when I write the first code in separate lines it won't give me None

a = np.arange(2,11)
a.resize((3,3))
print(a)

what is the difference between resize and reshape in this case and in what are the differences in general?

  • In the more general case, note that `reshape()` can only return an array with the original number of elements just shaped differently, whereas `resize()` can change the number of elements, i.e. the size as well as the shape. – Mark Setchell Aug 31 '20 at 08:37

2 Answers2

7

That is because ndarray.resize modifies the array shape in-place, and since you're assigning back to a you get None, as an in-place operation does not return anything. reshape instead returns a view of the array:

a = np.arange(2,11)
a.shape
#(10,)

a.resize((3,3))
a.shape
# (3, 3)

np.arange(2,11).reshape((3,3)).shape
# (3, 3)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Both reshape and resize change the shape of the numpy array; the difference is that using resize will affect the original array while using reshape create a new reshaped instance of the array.

Reshape:

     import numpy as np
     r = np.arange(16)
     
     print('original r: \n',r)
     print('\nreshaped array: \n',r.reshape((4,4)))
     print('\narray r after reshape was applied: \n',r)

output

original r: 
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]
 
reshaped array: 
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]
 
array r after reshape was applied: 
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]

Resize:

import numpy as np
r = np.arange(16)
 
print('original r: \n',r)
print('\nresized array: \n',r.resize((4,4)))
print('\narray r after resize was applied: \n',r)

output:

original r: 
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]
 
resized array: 
None
 
array r after resize was applied: 
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]

As you can see reshape created a reshaped new instance of the data while the original r stayed unchanged.And As you can see, resize didn’t create a new instance of r, the changes were applied to the original array directly.