It is often said that Python functions can return multiple values, but this isn't really true. Often the examples given to show Python returning multiple values is something like this:
def foo():
return 1, 3
a, b = foo()
But is that really returning multiple values? No. Well then how come we
were able to assign to a
and b
? Because we got multiple values returned,
right? No, this is just an application of tuple
unpacking. If
you're not convinced, consider than you could also do this:
c = foo()
Here, c
is assigned the value (1, 3)
which is a tuple. So foo()
is
actually returning a single value, a tuple, that contains two values that are
being unpacked in the assignment. This is no different than, say
a, b = 1, 3
where, again, the value on the right hand side of the =
is a 2-tuple. It
would perhaps be a little more clear what is going on if the function return
statement looked like
return (1, 3)
or even
return [1, 3]
Effectively those two are the same as the original. One value (a sequence) is being returned which contains 2 values which are unpacked in the assignment.
So as you can see, Python can't return multiple values after all.