Release a tuple's elements?

Viewed 41

I have a function which returns two numbers:

def f(x):
    return x, x+1

And I want to create a list based on another list , like this :

list_1 = [5, 8]

list_2 = [(100, f(x)) for x in list_1]

with the intended result to be [ (100, 5, 6), (100, 8, 9) ]

Instead I get : [ (100, (5, 6)), (100, (8, 9)) ]

How can I get the right list please ? Thanks

NOTE: The function f(x) is actually more complex and time-consuming and it is not efficient to either run it twice, or split in 2 functions, in order to get the elements separately.

1 Answers

Put * before f(x) (this will unpack the tuple):

def f(x):
    return x, x + 1


list_1 = [5, 8]
list_2 = [(100, *f(x)) for x in list_1]

print(list_2)

Prints:

[(100, 5, 6), (100, 8, 9)]
Related