3

Is it possible to unpack a list or tuple such that the values can be used as function parameters? I.e., how can I make the second line work?

f(1,2,3)
f(???([1,2,3]))

I'm currently doing this by hand, something like:

tmp1, tmp2, tmp3 = [1,2,3]
f(tmp1,tmp2,tmp3)

context: I don't have the ability to modify f(), but this is part of a code generator so funky solutions are not a problem.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
  • @NullUserException: That's for the function signatures. The syntax looks the same, but it is not the same functionality. – Martijn Pieters Dec 17 '13 at 19:12
  • @NullUserException: That is not to say this question is not a dupe, just not of the one you proposed. – Martijn Pieters Dec 17 '13 at 19:13
  • @Martijn I am pretty sure this has been asked before though. I'm on mobile so it's hard for me to look it up – NullUserException Dec 17 '13 at 19:13
  • I've got a bunch of dupes ... But it's hard to really pick which one ... http://stackoverflow.com/q/14565032/748858 , http://stackoverflow.com/q/11973028/748858 , etc. – mgilson Dec 17 '13 at 19:15
  • @mgilson: Time to stick to one and close everything else as dupes? – Martijn Pieters Dec 17 '13 at 19:19
  • @MartijnPieters -- Works for me. you have a preference? The title of the one proposed by alko seems most clear and the question is probably posed the best (most general/widely applicable). The answer is OK, but It seems to me that it could use more explanation ... :/ – mgilson Dec 17 '13 at 19:27
  • I'd discuss this in the [Python room](http://chat.stackoverflow.com/rooms/6/python). :-) – Martijn Pieters Dec 17 '13 at 19:28
  • The use of the "in-place" in the title is missleading into this construct: a,*b = [1,2,3] Please remove it.replace it with "in function-arguments" – ankostis Feb 17 '15 at 12:45

1 Answers1

13

Yes, you can use the *args (splat) syntax:

f(*[1, 2, 3])

See the call expressions documentation.

There is a keyword-parameter equivalent too, using two stars:

kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntax for specifying catch-all arguments in a function signature:

def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343