*args and **kwargs in Python

Why *args and **kwargs?

A function is useful in generating a reusable code. We call a function using specific arguments called function argument in Python.

Now let us try to understand its need.

For example in a simple program of multiply two numbers what will happen if we have passed three arguments instead of two.

Type error is thrown. In cases where we don’t know the no. of arguments we can use *args and **kwargs to pass variable no. of arguments.

Special Symbols for passing arguments:

Two special symbols are used in Python for passing variable no. of arguments in Python.

  • *args (Non-keyword argument)
  • **kwargs (keyword argument)

We use the * notation when we don’t know the no. of arguments.

*args:

               *args is used to pass a variable number of non-keyword arguments. * indicates the variable length of arguments. * before args denotes that arguments are passed as tuple. These arguments make tuple inside the function with same name as parameter excluding *

Using *args:

**kwargs:

               **kwargs allows us to pass a variable number of keyword arguments. ** before kwargs denotes that arguments are passed as dictionary. These arguments make dictionary inside the function with same name as parameter excluding **.

Using **kwargs:

Using both *args and **kwargs:

Argument order:

Argument order is important in function declarations, like in above example always

  • Regular arguments
  • *args
  • **kwargs

What will happen if we change order? let’s see!

Syntax error is raised.

Unpacking operator * :

The unpacking operator * is used to unpack and merge list, tuples.

Unpacking using *

Packing or merging list and tuples using *

Unpacking operator **

** is used to unpack and merge dictionaries.

Points to Note:

  • *args and **kwargs are special keywords for accepting variable number of arguments.
  • *args passes variable number of non-keyword arguments and performs operations on list, tuples
  • **kwargs passes variable number of keyword arguments and performs operations on dictionaries.
  • *args and **kwargs makes the function flexible.