What is *args and **kwargs in Python ?(Solved) - Python for Data Analytics

Python Programs | Python Tricks | Solution for problems | Data Cleaning | Data Science

What is *args and **kwargs in Python ?(Solved)

The special syntax, *args and **kwargs in function definitions 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 (positional) argument, and two more variable length arguments.

***********************Source Code************************************

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

test_var_args(1, "two", 3)


************************Output***************************************** 
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. 

***********************Source Code************************************

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

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

************************Output*****************************************

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

4 comments:

  1. Thank you for your information.it is very nice article.
    Python Training in Pune


    ReplyDelete
  2. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. best python classes in pune

    ReplyDelete
  3. Thanks for this post ,Very informative article.I got multiple new information from here and hope it's very helpful
    Best Python Classes in Pune

    ReplyDelete