Question about tensor's index

I run the code:

y = t[0, :] 
y += 1
print(t[0, :]) 

the result is :

tensor([5, 9, 9])
tensor([5, 9, 9])

y and t[0,:] share memory. But after I changed the index, I run the new code:

y = t[0, [1, 2]]
y += 1
print(t[0, [1, 2]]) 

the result is:

tensor([10, 10])
tensor([9, 9])

y and t[0, [1, 2] don’t share memory。Do you know the reason? Any help would be appreciated, thank you.


This is because advanced indexing methods (fancy things in brackets) try to return view but they cannot always do it. So you should not rely on it returning the same memory.

If you just want to change this part of t, you can use t[0, [1, 2]] += 1 that will change t inplace properly.