Search code examples
pythonfunctioniooutput

manage the number of outputs of a function in python


I want to make a function of returning the variable number of outputs.

I've tried out1, out2 = function()[:-1]and out1, out2 = function()[:2] and changing function() by using if statement

def function():
    a=1;b=2;c=3
    return a,b,c
out1, out2 = function() ### Line number 4

I want to do "Line number 4" only by changing function() without if statement. out1, out2 = function() Of course, this shows ValueError: too many values to unpack (expected 2)


Solution

  • Don't put several variables in the function call, instead of this:

    out1, out2 = function()
    

    do this:

    values = function()
    print "I've got", len(values), "return values"