How to use *args and **kwargs in Python

This is my OLD blog. I've copied this post over to my NEW blog at:

You should be redirected in 2 seconds.

Or, How to use variable length argument lists in Python.

The special syntax, *args and **kwargs in function declarations is used to pass a variable number of arguments to a function. The single asterisk form (*args) is used to pass a non-keyworded, variable-length argument list, and the double asterisk form is used to pass a keyworded, variable-length argument list. Here is an example of how to use the non-keyworded form. This example passes one formal argument, and two more variable length arguments.

def test_var_args(farg, *args):
    print "formal arg: %s" % farg
    for arg in args:
        print "another arg: %s" % arg

test_var_args(1, 'two', 3)

formal arg: 1
another arg: two
another arg: 3

Here is an example of how to use the keyworded form. Again, one formal argument and two keyworded variable arguments are passed.

def test_var_kwargs(farg, **kwargs):
    print "formal arg: %s" % farg
    for key in kwargs:
        print "another keyword arg, %s: %s" % (key, kwargs[key])

test_var_kwargs(farg=1, myarg2='two', myarg3=3)

formal arg: 1
another keyword arg, myarg2: two
another keyword arg, myarg3: 3

See also Section 5.3.4 in the Python Reference Manual

Reference: Core Python Programming, Second Edition, Section 11.6


Skawaii said...

Thanks for the succinct explanation of *args and **kwargs. You made it nice and easy to understand.

Julien said...

thanks for this explanation. It's pretty cool to have such informations easy to understand.


This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.