0

So I have a function that takes two parameters and another function that returns those two parameters. However I can't seem to figure out how to do this. In order to simplyfy my code I will make up funcions.

def my_function(x, y):
    return x + y

def get_x_and_y():
    x, y = [5, 10]
    return x, y

print(my_function(get_x_and_y()))

So this gives an error and I'm not sure how to do this.

I know this might be answered but I'm not quite sure how to word it on google, and I have looked for a while.

  • 2
    `print(my_function(*get_x_and_y()))`. –  Sep 10 '17 at 16:21
  • 2
    See also eg https://stackoverflow.com/questions/7745952/how-to-expand-a-list-to-function-arguments-in-python. The search term you'd be looking for is "parameter expansion" (or argument expansion). –  Sep 10 '17 at 16:22
  • I'm slightly amused because this kind of code would have just worked [in Perl](https://ideone.com/v7ccRl). – melpomene Sep 10 '17 at 16:25
  • 2
    Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Matteo Ragni Sep 10 '17 at 16:27
  • @melpomene of course, the (counter) question would be: what if you'd have to pass a tuple as a single argument instead, in Perl? Would Perl do try to do the right thing by inferring from the function signature? –  Sep 10 '17 at 17:11
  • @Evert Perl doesn't really have tuples. You'd have to pass an array (like `[$x, $y]`). And no, nothing would be inferred. – melpomene Sep 10 '17 at 17:14

2 Answers2

0

The answer for you question is here: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?. As suggested in Everts comment:

print(my_function(*get_x_and_y()))

where the asterisk performs the parameter expansion (also called splatting in Ruby, I love this term :) )

Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34
0

Functions in Python always return exactly one item. In the case of get_x_and_y, that item is a tuple of length two.

So your current code is calling my_function with just one parameter, a tuple. You want to expand that tuple into the function's arguments, using *:

my_function(*get_x_and_y())
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328