Issue
When initializing multiple variables in Python is seems that every variable is different (i.e. not a reference) :
>>>x = y = z = 6
>>>x=5
>>>y=0
>>>print(x,y,z)
>>>5 0 6
but when I am using a numpy array every variable is actually a reference:
import numpy as np
x = y = z = 6*np.ones(1)
x[0] = 5
y[0] = 0
print(x,y,z)
[0.] [0.] [0.]
Why am I seeing this difference?
Solution
This is down to a difference in types. Integers are not passed by reference, so each variable gets its own copy of the number. If you look at a different object like a list though:
x = y = z = [0,1,2]
x[0] = 2
print(x, y, x)
[2, 1, 2], [2, 1, 2], [2, 1, 2]
this is also passed by reference, so they all change together.
Strings and integers are the main examples I can think of that you the value, while everything else (I think) is a reference.
Interesting aside related to this: in place operations behave differently for strings and integers vs other objects. For example:
x = 1
print(id(x))
x += 1
print(id(x))
behaves differently to
y = []
print(id(y))
y += [1]
print(id(y))
You can see in the first instance a new object is now assigned to the x variable, while in the second the y variable is the same object.
Answered By - PirateNinjas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.