Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 617
dcnicholls Avatar asked Oct 22 '13 01:10

dcnicholls


2 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()
like image 140
Jonathon Reinhart Avatar answered Oct 24 '22 22:10

Jonathon Reinhart


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

my_array, my_variable = my_function()
like image 38
Andy Avatar answered Oct 24 '22 22:10

Andy