Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more pythonic way of exploding a list over a function's arguments?

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])

like image 323
blippy Avatar asked Dec 15 '12 10:12

blippy


1 Answers

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'}
like image 102
K Z Avatar answered Sep 18 '22 23:09

K Z