What happens in the process of a[0],a[1] = a[1], a[0]?

Viewed 81

I find a Incomprehensible phenomenon this afternoon.I want to exchange two lines in ndarray shown as following code.

import numpy as np

a = np.random.randint(0, 40, size=(4, 4))
a = a + a.T
b = a.copy()
print(a)
b[1], b[3] = b[3], b[1]
print(b)

But an unexpected result came.The printing result as follows

[[60 64 12 33]
 [64 30 29 60]
 [12 29 40 64]
 [33 60 64 76]]

[[60 64 12 33]
 [33 60 64 76]
 [12 29 40 64]
 [33 60 64 76]]

i know a,b = b,a is effective.i want to know what difference between them? Can u talk about this question in terms of memory? thank u in advance!

1 Answers

b[3] and b[1] are views into the original array. They don't copy their data. This is what you want most of the time.

So when you write b[1], b[3] = b[3], b[1] first the third row gets assigned to the first row, changing the array b. At this point b[1] has been changed, so when b[3] = b[1] happens your original data is gone.

b[[1, 3]] = b[[3, 1]] does what you want (also known as 'fancy indicing', this doesn't create views).

Related