DiogoNeves
DiogoNeves

Reputation: 1777

How to append the second return value, directly to a list, in Python

If a function returns two values, how do you append the second value directly to a list, from the function result? Something like this:

def get_stuff():
    return 'a string', [1,2,3,5]

all_stuff = [6,7]
# How do I add directly from the next line, without the extra code?
_, lst = get_stuff()
all_stuff += lst

Upvotes: 1

Views: 582

Answers (2)

BigBrownBear00
BigBrownBear00

Reputation: 1480

Try all_stuff += zip(get_stuff())[1]

Upvotes: -2

Cory Kramer
Cory Kramer

Reputation: 117856

You can index a tuple using the same indexing you would for a list []. So if you want the list, which is the second element, you can just index the element [1] from the return of the function call.

def get_stuff():
    return 'a string', [1,2,3,5]

all_stuff = [6,7]
all_stuff.extend(get_stuff()[1])

Output

[6, 7, 1, 2, 3, 5]

Upvotes: 5

Related Questions