Is there a better way to code variable number of return arguments?

Ethan Furman ethan at
Thu Oct 8 19:05:14 CEST 2009

Dr. Phillip M. Feldman wrote:
> I currently have a function that uses a list internally but then returns the
> list items as separate return
> values as follows:
> if len(result)==1: return result[0]
> if len(result)==2: return result[0], result[1]
> (and so on).  Is there a cleaner way to accomplish the same thing?

To elaborate on Paul's answer, returning the list will also unpack it if 
you have it set up that way.  E.g.

def func(alist):
    return alist

some_list = [1, 2]
this, that = func(alist)

At least, in 2.5.4 this works.  :-)

Mind you, if you don't have the correct number of return names to match 
the unpacking you'll get the normal errors from that.

Hope this helps!


More information about the Python-list mailing list