Reputation: 73
I am confused about below two codes:
1st code: Changes getting reflected in both array
import numpy as nm
ab=nm.arange(10)
ba=ab
ba[0]=99
print(ba)
print (ab)
Output:
ba=[99 1 2 3 4 5 6 7 8 9]
ab=[99 1 2 3 4 5 6 7 8 9]
2nd code: Changes NOT getting reflected in both array
import numpy as nm
ab=nm.arange(10)
ba=ab
ba=ab-ab
print(ba)
print(ab)
Output:
ba=[0 0 0 0 0 0 0 0 0 0]
ab=[0 1 2 3 4 5 6 7 8 9]
Can anybody please explain this? I want to understand why is it happening? I can see new address is allocated in 2nd case but why is not overwriting the data like in 1st case?
Upvotes: 0
Views: 133
Reputation: 3232
The variable that holds the array actually holds the memory address where the array is located, by doing ba=ab
you're setting the same address for both arrays, so if you change one of them the changes will be reflected in the other, but by doing ba=ab-ab
you're overwriting this address with the result of an evaluation, and as it is new data it has to be stored in a new memory address.
Upvotes: 2