Can one return a variable number of outputs in python function

Viewed 11

Naive implementation

def f(*args):
    return args

print(f(1))
print(f())

>> (1,)
>> ()

Implementation that does more or less what I want

def f2(*args):
    if len(args) > 1:
        return args
    elif len(args) == 1:
        return args[0]
    else:
        return None
    
print(f2(1))
print(f2())

>> 1
>> None

Question: Is there a simpler way to implement f2? It feels somewhat inconsistent that regular return statement can return a single value, but return of parameterized inputs has to be specifically converted from tuple back to value.

0 Answers
Related