Search code examples
pythonpython-2.7iterable-unpacking

How to unpack a function-returned tuple?


I want to append a table with a list of function-returned values, some of them are tuples:

def get_foo_bar():
    # do stuff
    return 'foo', 'bar'

def get_apple():
    # do stuff
    return 'apple'

table = list()
table.append([get_foo_bar(), get_apple()])

This yields:

>>> table
[[('foo', 'bar'), 'apple']]

But i need the returned tuple to be unpacked into that list, like so:

[['foo', 'bar', 'apple']]

Since unpacking the function call [*get_foo_bar()] won't work, i assigned two variables for recieving the tuple's values and appended them instead:

foo, bar = get_foo_bar()
table.append([foo, bar, get_apple()])

This works, but can it be avoided?


Solution

  • Use .extend():

    >>> table.extend(get_foo_bar())
    >>> table.append(get_apple())
    >>> [table]
    [['foo', 'bar', 'apple']]
    

    Or, you can concatenate tuples:

    >>> table = []
    >>> table.append(get_foo_bar() + (get_apple(),))
    >>> table
    [('foo', 'bar', 'apple')]