I can't seem to find an explanation anywhere for this...
Suppose I have a vector y initialized to all zeroes:
from numpy import *
y = zeros(5)
It could also be a plain python array, I don't think it really matters.
I noticed that the behavior of the for x in y: statement is that it makes a copy of each element in y, thus when you modify x, it does not modify y.
for x in y:
x = 1
print y
output : array([ 0., 0., 0., 0., 0.])
My question is the following : Why is that so? I thought in Python everything was all byReference and that there is very little byValue passing around?
How could I do the following, using referenced variables? Doing the following seems to work :
for i in range(len(y)):
y[i] = 2*rand()-1
But from what I know about Python, this is wrong and I believe it will be slow when I start using vectors of thousands or millions of values.
What else could I do?
You can replace this:
y = np.zeros(5)
for i in range(len(y)):
y[i] = 2*rand()-1
with:
y=2*np.random.rand(5)-1
If y is a Python sequence (tuple, list, array, etc) or Numpy array,
for x in y:
iterates through y, setting x to each element in y.
If the elements are immutable objects like str, int, float or a Numpy numeric type,
then changing the value of x does not change the value in y.
If the elements are mutable objects, such as a list, then mutating the list will affect y.
Think of it this way: x is "pointing" to an object:
y---> [o----o----o----o]
^
|
x
When you write an assignment statement:
x += 1
Now you are reassigning x to "point" to a different object:
y---> [o----o----o----o]
x---> o
On the other hand, if you mutate a list with, say, x.append(1), then
x still points to the same object (e.g. a list), but you've mutated the contents of that list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With