0

I got this code here:

a = np.zeros([32,32])
b = np.index_exp[:3,:3]
c = a[b]
c=1

a will still be a bunch of zeros. It won't change because of what happens to c.

But if I do this

a = np.zeros([32,32])
b = np.index_exp[:3,:3]
c = a[b]
c[:]=1

Now a changes. Why? It looks like in the first example I completely reassigned c, but in the second I assigned all of the values of c and then there was a reference? Anyone know the specifics?

James Huang
  • 848
  • 1
  • 7
  • 35
  • Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – ouroboros1 Nov 13 '22 at 08:21
  • 1
    Does this answer your question? [What's the point of assignment to slice?](https://stackoverflow.com/questions/56675075/whats-the-point-of-assignment-to-slice) – ILS Nov 13 '22 at 08:36
  • And this one, [Slice vs normal assignments](https://stackoverflow.com/questions/25470184/slice-vs-normal-assignments) – ILS Nov 13 '22 at 08:37
  • In the first you assign `1` to `c`, breaking the original link to `a`. It doesn't matter what the first `c=...` was. With the second you modify the values of the object referenced by `c`, – hpaulj Nov 13 '22 at 14:12
  • The second is effectively `a[:3,:3]=1`. `c` is `a[:3,;3]`, a view of `a`. Modifying values of the view results in modifying its `base`. Having an idea of how arrays are stored, and the distinction between a `view` and `copy` helps. Your use of `np.index_exp` isn't a significant factor here. – hpaulj Nov 13 '22 at 16:28

0 Answers0