2

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?

2
  • @tom10 Oh, looks like I missed Python 101..What's the name for this? dereference? Commented Jul 23, 2015 at 2:46
  • @bl4cksun its called argument unpacking Commented Jul 23, 2015 at 3:43

1 Answer 1

5

You are looking for unpacking. You should try -

sum(*foo())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.