Why doesn't this slicer example work in NumPy the same way it works with standard lists?

Why doesn't this slice example give the same results as standard lists? It works as if it first evaluates an[:2] = bn[:2] , and then bn[:2] = an[:2] .

 import numpy as np l1 = [1, 2, 3] l2 = [4, 5, 6] a = list(l1) b = list(l2) an = np.array(a) bn = np.array(b) print(a, b) a[:2], b[:2] = b[:2], a[:2] print(a, b) print(an, bn) an[:2], bn[:2] = bn[:2], an[:2] print(an, bn) 

Output:

 -------------------- [1, 2, 3] [4, 5, 6] [4, 5, 3] [1, 2, 6] -------------------- [1 2 3] [4 5 6] [4 5 3] [4 5 6] -------------------- 

If I do this, everything works:

 dummy = an[:2] an[:2] = bn[:2] bn[:2] = dummy 
+5
source share
1 answer

For lists, a[:2] is a copy of the list with the first two elements, for numpy arrays, this is just a link. You must make a copy, explicitly:

 an[:2], bn[:2] = bn[:2].copy(), an[:2].copy() 
+6
source

Source: https://habr.com/ru/post/1244391/


All Articles