return multiple objects

Rhodri James rhodri at wildebst.demon.co.uk
Thu Feb 5 22:37:24 EST 2009


On Fri, 06 Feb 2009 03:03:01 -0000, Vincent Davis  
<vincent at vincentdavis.net> wrote:

> Is it correct that if I want to return multiple objects from a function I
> need to in some way combine them?
> def test1():
>     a = [1,3,5,7]
>     b = [2,4,6,8]
>     c=[a,b]
>    return a, b # this does not work?
>    return [a, b] # does not work?
>    return c # this works but I don't like it, , is there a better way?

Strictly speaking, you can only return one object from a function.   
However,
that one object can be a container (list, tuple, dict, set, or what have
you) that contains multiple objects.  Tuples are a popular choice:

   return a, b

...but almost any ordered type would do, because you can automagically
unpack the results if you want to:

   x, y = test1()

(You might be expecting brackets around the "a, b" and the "x, y", and
you'd be sort of right.  The brackets (parentheses) for tuples are
optional, except for a couple of cases where you *have* to put them
in to avoid ambiguity.  I tend to put them in always, but leaving them
out in cases like this seems to be normal practice.)

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list