0

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.

1
  • don't give your vars the same name as a function. Commented Mar 28, 2018 at 21:43

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

Comments

1

You should return from your function

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

Then you can assign the return value

mean = func()

2 Comments

This means func is operating on a assuming it is global; which I don't recommend.
Either that or a is (hopefully) a variable local within the function func and is some intermediate value

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.