Python *,**,*args and **kwargs

This blog post particularly,will be more on the practical side of things.
Something more of like “learning by doing” kind of stuff.So lets jump onto it right away!

First off, we have * being passed alongside with a parameter.
Now we all know of what are parameters or arguments.

def my_function(arg):
print arg
>>>my_function(“rahul”)
rahul

We need to see HOW * changes (or modifies) this simple process.
Suppose we have a function that takes in two values and adds them.

def add_function(a,b):
return a+b

If we were to keep it plain simple and easy, we could have typed in

>>>add_function(1,2)
3

But what if we created a list that had the values to be passed into the function? We could achieve that by using “*”

>>> my_list = [1,2]
>>> print add_function(*my_list)
3

Notice here, that the number of elements in the list my_list should be equal to the number of arguments that the function my_function() can take! Otherwise you will see errors.

Now coming onto to *args, we have a little twist. When used with function arguments, it takes a tuple!
See here,

def print_names(*args):
print args
>>> print_names(“rahul”,”lakhanpal”)
(‘rahul’, ‘lakhanpal’)

Cool! You can use any number of arguments with this function, and it will always give you the results.
Here is a quick recap of what we did in simple code snippet as shown below.

Lets move on to “**” and “*kwargs” now.

Editing the initially created addition function to include the default values for parameter , we will have

def add_function(a=1,b=3):
return a+b
>>> print add_function()
4

Lets define a dictionary this time, and put these value into it.

>>> d = {‘a’:1,’b’:3}
def add_function(**d):
return sum([i for i in d.values()])
>>> print add_function()
4

So as you see, we have passed a dictionary and just provided the parameters of the function with the values.
Or in another sense , the parameter act as keys of a dictionary.

Similar to the use of *args, we have **kwargs. 
kwargs takes all the values in the form of a dictionary and can act over any amount of key:value pairs been passed into it.

def print_names(**kwargs):
print kwargs
>>> print_names(fname=”rahul”,sname=”lakhanpal”)
{‘sname’: ‘lakhanpal’, ‘fname’: ‘rahul’}
>>>

A quick recap of what all we have learned till now in a single big example.
Watch it closely.

I hope the above explanation will help resolve lots of problems while implementing *args and **kwargs.

Happy Coding!