Is there a more pythonic way of exploding a list over a function's arguments?
14,363
Solution 1
Yes, use foo(*i)
:
>>> foo(*i)
6
You can also use *
in function definition:
def foo(*vargs)
puts all non-keyword arguments into a tuple called vargs
.
and the use of **
, for eg., def foo(**kargs)
, will put all keyword arguments into a dictionary called kargs
:
>>> def foo(*vargs, **kargs):
print vargs
print kargs
>>> foo(1, 2, 3, a="A", b="B")
(1, 2, 3)
{'a': 'A', 'b': 'B'}
Solution 2
Yes, Python supports that:
foo(*i)
See the documentation on Unpacking Argument Lists. Works with anything iterable. With two stars **
it works for dicts and named arguments.
def bar(a, b, c):
return a * b * c
j = {'a': 5, 'b': 3, 'c': 2}
bar(**j)
Author by
blippy
Updated on June 17, 2022Comments
-
blippy almost 2 years
def foo(a, b, c): print a+b+c i = [1,2,3]
Is there a way to call foo(i) without explicit indexing on i? Trying to avoid foo(i[0], i[1], i[2])