Python: Can a Function Return an Array and a Variable?

Is there a simple way to get a function to return a np.array and a variable?

eg:

my_array = np.zeros(3)
my_variable = 0.

def my_function():
    my_array = np.array([1.,2.,3.])
    my_variable = 99.
    return my_array,my_variable

my_function()

so that the values calculated in the function can be used later in the code? The above ignores the values calculated in the function.

I tried returning a tuple {my_array, my_variable} but got the unhashable type message for np.array

DN

6

4 Answers

Your function is correct. When you write return my_array,my_variable, your function is actually returning a tuple (my_array, my_variable).

You can first assign the return value of my_function() to a variable, which would be this tuple I describe:

result = my_function()

Next, since you know how many items are in the tuple ahead of time, you can unpack the tuple into two distinct values:

result_array, result_variable = result

Or you can do it in one line:

result_array, result_variable = my_function()

Other notes related to returning tuples, and tuple unpacking:

I sometimes keep the two steps separate, if my function can return None in a non-exceptional failure or empty case:

result = my_function()
if result == None:
    print 'No results'
    return
a,b = result
# ...

Instead of unpacking, alternatively you can access specified items from the tuple, using their index:

result = my_function()
result_array = result[0]
result_variable = result[1]

If for whatever reason you have a 1-item tuple:

return (my_variable,)

You can unpack it with the same (slightly awkward) one-comma syntax:

my_variable, = my_function()

It's not ignoring the values returned, you aren't assigning them to variables.

my_array, my_variable = my_function()
2

easy answer

my_array, my_variable = my_function()

After the definition of my_function, use my_function = np.vectorize(my_function).
For example,

def jinc(x):
    if x == 0.0:
        return 1
    return 2*j1(x)/x

jinc = np.vectorize(jinc)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest