I recently reduced a bug in some code to being a result of the following behaviour:
>>> arr = np.zeros(10)
>>> value = 0
>>> dictionary = {"key":[arr,value]}
>>> dictionary["key"][0]
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> dictionary["key"][1]
0
>>> dictionary["key"][0]+=1
>>> dictionary["key"][1]+=1
>>> dictionary["key"][0]
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>> dictionary["key"][1]
1
>>> arr
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>> value
0
Resulting in:
>>> dictionary["key"][0] is arr
True
>>> dictionary["key"][1] is value
False
Probably a silly question, but what causes this?
In the case of the numpy array, you have the same object assigned with the name arr
and inside your dictionary. As such, when you modify it you see the change appear for both, they're the same object after all, and numpy arrays are mutable.
For the integer, when you do dictionary["key"][1]+=1
you are creating a new integer inside the dictionary, this is because integers are immutable [1]. This means that the two integers (value
and dictionary["key"][1]
) are different objects, and so one is modified but the other is not.
[1] It might look like x = 2; x += 1
is operating on the same object, after all +=
should do "in-place" operations, but it's not because of the immutability. Behind the scenes you're actually re-binding x
with a new integer object, as such they have the same name, but are different objects.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments