Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to call a function with argument list in Python?

In the following code

def baz1(foo, *args): # with star\n     foo(*args)\ndef baz2(foo, args): # without star\n    foo(*args)\ndef foo2(x, y, z):\n    print x+y+z\nbaz1(foo2, 2, 3, 4)\nbaz2(foo2, [2, 3, 4])

I am able to pass an argument list to a python function both implicitly and explicitly and call it. How was this made possible? 


1 Answer
Manogna
def baz1(foo, *args):

The * next to args means "take the rest of the parameters given and put them in a list called args".

In the line:

    foo(*args)

The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters.

in foo2, the list is passed explicitly, but in both wrappers args contains the list [1,2,3].

def baz1(foo, *args): # with star
     foo(*args)
def baz2(foo, args): # without star
    foo(*args)
def foo2(x, y, z):
    print x+y+z
baz1(foo2, 2, 3, 4)
baz2(foo2, [2, 3, 4])

OUTPUT

9
9

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.