How To Understand *args and **kwargs In Python

Introduction 

 
It took some time to figure out what is behind *args and **kwargs. Finally, I understood it and now I want to share it with you all here. First of all, you need to know what you need to understand. Here is the asterisk (*), not the “args” and “kwargs”. So, if you write def foo(*params, **oparams) and def foo(*args, **kwargs), they both will behave similarly.
  1. Understand Using Single Asterisk(*)
     
    A single asterisk* is used to pass a varied length of arguments. Here is an example of how to use *,
    1. def foo(a, *b):  
    2.    def foo(a, *b):   
    3.          print "normal variable: ", a   
    4.          print "first argument: ", b[0]   
    5.    print "second argument: ", b[1]   
    6.    print "third argument: ", b[2]   
    7. foo('amit singh'1,2,3,4,5)  
    In this example, “a” is a single variable while “b” is a varied length of the argument. Thus, the first argument will be passed to “a” where the next variable will be passed to “b”. Thus, all arguments (1,2,3,4,5) will be passed to “b” while only “amit singh” will be passed to “a”.
     
  2. Understand Using Double Asterisks(**)
     
    A double asterisk (**) is used for varied arguments with a key. Here is an example.
    1. def foo(a, **c):   
    2.    print "normal variable: ", a   
    3.    print "first argument: ", c['one']   
    4.    print "second argument: ", c['two']   
    5.    print "third argument: ", c['three']   
    6. foo('amit singh', one=1, two=2, three=3)  
    In this example, the first argument is passed to “a”, while the next variable will be passed to “c”. Please notice that the way we pass the variable is different from single asterisk(*). For two asterisks (**), we need to define a key for each value we pass. Note that the key is “one”, “two” and “three” while the values are everything after “=”. The number of arguments passed may be varied.
     
  3. Understand Using Both Single Asterisk(*) And Double Asterisks(**)
     
    To make everything even more clear, here is another example to combine both single asterisk and double asterisks.
    1. def foo(a, *b, **c):   
    2.    print "normal variable: ", a   
    3.    print "arg 0: ", b[0]  
    4.    print "arg 1: ", b[1]  
    5.    print "arg 2: ", b[2]  
    6.    print "first argument: ", c['one']   
    7.    print "second argument: ", c['two']   
    8.    print "third argument: ", c['three']   
    9. foo('amit singh'1234, one=1, two=2, three=3)  
Hope this article has made you understand what *args and **kwargs are and when to to use this.