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

Hendrik van Rooyen hendrik at
Fri Oct 9 08:36:12 CEST 2009

On Thursday, 8 October 2009 18:41:31 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?

Why do you not change the list into a tuple and return the tuple, and let 
automatic unpacking handle it?

As I see it, the problem is not in the return, but in the call - how do you 
know now, which of the following to write:

answer = thing(params)
answer0,answer1 = thing(params)
answer0,answer1,answer2 = thing(params)
answer0,answer1,answer2,answer3 = thing(params)

and so on...

probably best to write:

answers = thing(params)

for answer in answers:
    do something with answer

- Hendrik

More information about the Python-list mailing list