yobro97
yobro97

Reputation: 1145

Assign numpy array to a pre initialized variable

I have to make this piece of code work.

mean = []

def func():
    mean = np.mean(a,axis=0);
print mean

But on printing mean I get an output []. How can I assign np.mean to mean? PS: I am a beginner in numpy so I am quite confused on how variable assignment works here.

Upvotes: 0

Views: 207

Answers (2)

cs95
cs95

Reputation: 402363

The mean inside func isn't the same as the mean outside. When you assign mean = ... inside func, you are creating a new variable in func's local scope - this mean is completely different from the mean defined outside, in global scope. Furthermore, the local variable with the same name hides the global variable, so in the end, the global variable is not touched.

The basic fix would be to declare mean as a global variable inside func and use the out param:

mean = np.empty(...)

def func(a):
    global mean
    np.mean(a, axis=0, out=mean) # you don't need the trailing semicolon either

However, for the sake of maintainable code I'd recommend not working with global variables at all when you can avoid it. Instead pass a as a parameter to func and return the result:

def func(a):
    return np.mean(a,axis=0)

mean = func(a)

The only event I'd recommend the former method is when it would make more sense performance wise. However, for a simple thing like computing the mean, why even declare a function in the first place?

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

You should return from your function

def func():
    return np.mean(a,axis=0);

Then you can assign the return value

mean = func()

Upvotes: 1

Related Questions