0

I am having trouble understanding, why I get different values in the following two cases:

-Case 1:

def myfunc(a,b,c):
    xx = a+b
    yy = b+c
    return xx, yy

q,w = myfunc(1,2,3)

print(q,w)

Output 1: 3 5

-Case 2:

import numpy as np

q=w=np.zeros(3)

def myfunc(a,b,c):
    xx = a+b
    yy = b+c
    return xx, yy


for i in range(3):
    q[i],w[i] = myfunc(1,2,3)

print(q,w)

Output 2: [5. 5. 5.] [5. 5. 5.]

In the second case, both arrays have their entries equal to 5. Could someone explain, why?

1 Answer 1

1

I won't talk about the first case because it's simple and clear. For the second case, you have defined the variables q and w as following

q=w=np.zeros(3)

In this case, what ever changes you make in q they will be applied to w because they q and w have the same address.

When you run this:

q[i],w[i] = myfunc(1,2,3)

q[i] gets the value 3 and w[i] gets the value 5 and since q and w have the same address, q[i] will get the value 5 as well. That explains why you have 5 every time.

If you want to solve it, change the variable definition line from:

q=w=np.zeros(3)

to :

w=np.zeros(3)
q=np.zeros(3)
Sign up to request clarification or add additional context in comments.

4 Comments

More precisely, q and w are both references to the same object created by np.zeros(3). (There is no notion of "address" in Python.)
Thank you, that helps. I thought I would save space by using q=w=np.zeros(3) instead of w=np.zeros(3) q=np.zeros(3), but did not know they would be assigned to the same memory address.
@chepner, yes, that makes sense! Thank you!
@numpy There is no "they"; you only created one object, then defined two references two it. Simple assignment never creates a copy in Python. Be sure to read nedbatchelder.com/text/names.html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.