Python *args and **kwargs

What is *args ??

*args  allows us to pass variable number of arguments to the function. Let’s take an example to make this clear.

Suppose you created a function to add two number like this.

As you can see this program only accepts two numbers, what if you want to pass more than two arguments, this is where *args  comes into play.

Now you can pass any number of arguments to the function like this,

Note: name of *args  is just a convention you can use anything that is a valid identifier. For e.g *myargs is perfectly valid.

What is **kwargs ?

**kwargs allows us to pass variable number of keyword argument like this func_name(name='tim', team='school')

Expected Output:

Using *args and **kwargs in function call

You can use *args  to pass elements in an iterable variable to a function. Following example will clear everything.

Note: This works only when number of argument is same as number of elements in the iterable variable.

Similarly you can use **kwargs  to call a function like this

Note: For this to work 2 things are necessary:

  1. Names of arguments in function must match with the name of keys in dictionary.
  2. Number of arguments should be same as number of keys in the dictionary.

Leave a Reply

Be the First to Comment!

Notify of