Search code examples
pythontuplesunpack

Python: easiest way to flatten a tupple containing another tupple from a function


My code is like this:

def f1():
    return 2, 3

def f2():
    return 1, f1()

I can do:

a, (b, c) = f2()

I want to do:

a, b, c = f2()

All the solutions I could find require using a lot of insane parenthesis/brackets, or creating an identity function to use * operator. I would like to only modify f2().

Is there something simpler?


Solution

  • Instead of using 1, f2(), use tuple concatenation:

    def f2():
        return (1,) + f1()
    

    As mentioned in a comment, you could also do this:

    def f2():
        x,y = f1()
        return 1, x, y
    

    You could also do this:

    def f2():
        return (lambda *args: args)(1, *f1())
    

    That is a little long, but it has an advantage over the x,y = f1() solution because this way f1() can return a tuple with any number of elements.