Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 408
rypel Avatar asked Jul 01 '13 09:07

rypel


1 Answers

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')]
like image 56
TerryA Avatar answered Sep 23 '22 21:09

TerryA