2

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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Wartin
  • 1,965
  • 5
  • 25
  • 40

1 Answers1

2

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)]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 2
    Note for OP: this is called the "splat operator". – Code-Apprentice Aug 25 '21 at 22:18
  • 1
    @Code-Apprentice isn't it called unpacking operator? Splat is in Ruby. – Anirban Nag 'tintinmj' Aug 25 '21 at 22:48
  • @AnirbanNag'tintinmj' "unpacking operator" might be used as well, but I haven't personally heard it called that. See https://stackoverflow.com/questions/2322355/proper-name-for-python-operator for a list of opinions on the matter. Googling for "python splat operator" gives some helpful results. Since google ignores punctuation, having a name for an operator helps with searches. – Code-Apprentice Aug 25 '21 at 22:51
  • @AnirbanNag'tintinmj' I wouldn't be surprised that Python borrows the term "splat" from Ruby (or vice versa). – Code-Apprentice Aug 25 '21 at 22:56