qweruiop
qweruiop

Reputation: 3266

How to pass tuple to function as separate variables

When returning multiple variables from a Python function, returning a tuple is the most convenient solution to me. However, it lacks convenience when chaining the return value with another function taking separate variables as input. For example, say we have

def foo():
    return (1,2)

def sum(a, b):
    return a+b

And in this case, the following chaining doesn't work

sum(foo())

I know one solution, namely to change the function sum to take a tuple as input rather than 2 vars, i.e.

def sum2((a, b)):
    return a+b

Now the chaining sum2(foo()) works, but it's a bit awkward, isn't it? I wound rather change foo() because sum() might has been used by others. What is a nice solution to this?

Upvotes: 2

Views: 181

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 91009

You are looking for unpacking. You should try -

sum(*foo())

Upvotes: 5

Related Questions