Python: Can a function return an array and a variable?
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()
easy answer
my_array, my_variable = my_function()