Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Different function outputs for integers and numpy arrays

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading