Vermz
Vermz

Reputation: 33

How does iteration work in function

here's my problem. Sorry for the previous post which was not clear at all.

so here's an example:

import numpy as np

x=np.arange(1,100,1)
y=z=x*0

def func(h,g):
    for i in range(1,50):
        h[i]=i+1
        g[i]=i*2

func(z,y)
print z-y

In this example z and y give the same answer, but why is that so? In the function it is not supposed to give the same answer?

Upvotes: 2

Views: 131

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

You're setting y and z to both point to the same object. This line:

y=z=x*0

creates one new object, x*0, then sets both y and z to refer to it. Thus, h and g in your function are the same object, and the updates overwrite each other.

If you want to have two independent objects, create them independently:

y=x*0
z=x*0

Upvotes: 4

Related Questions