How to unpack the tuple returned by the function?

I want to add a table with a list of returned functions, 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 gives:

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

But I need the returned tuple to be unpacked into this list, for example:

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

Since unpacking the function call [*get_foo_bar()] will not work, I assigned two variables to get the tuple values ​​and added them instead:

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

It works, but can it be avoided?

+4
source share
1 answer

Use .extend() :

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

Or you can link tuples:

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

Source: https://habr.com/ru/post/1489060/


All Articles