*args and **kwargs in Python

Python accepts a list or a dictionary as arguments in function. This is very useful. Look at this code example:

def TestArgs(titleid, typename, *args, **kwargs):
    print titleid,typename
    print "**************"
    for val in args:
         print val

    for k,v in kwargs.iteritems():
        print k,v

if __name__ == '__main__':
    TestArgs(69,"ps4", 1,"2","6")

The output is:
69 ps4

For *args, it is a list argument, while **kwargs is a key value argument. These two arguments must be put at the end of function parameters and **kwargs comes after *args.  Both *args and **kwargs can be absent. Like example above, there is no **kwargs. The **kwargs also can construct when function is called:

TestArgs(65,"ps4", name="abc", number="123")

The output is:

65 ps4
name abc
number 123

At the called above, the *args is ignore and the dictionary is create as {“name”:”abc”, “number”:”123″} when calling  TestArgs.

Also, if need to pass an exist dictionary or list , the call should be like this:

if __name__ == '__main__':
    my_lst = [1,2,3,4,5]
    my_dst = {"name":"abc", "number":"123"}
    TestArgs(65,"ps4", *my_lst, **my_dst)

Notice that, if there is not * mark before my_lst or ** before my_dst, the function will process my_lst as an single element in *arg list. Like [[1,2,3,4,5]] and single element at **kwargs: {{“name”:”abc”, “number”:”123″}} where the length of args and kwargs are 1.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s