Skip to content

Understanding Args and Kwargs in Python

What are Args?"

  1. *args are used to pass non-keyword arguments. Examples of non-keyword arguments are fun(12,14), fun(“value1”,“value2”).
  2. *args are usually used to prevent the program from crashing. If we do not know, numerous parameters will be passed to the function. This is used in other programming languages.

It makes it easy to use any number of arguments without having to change your code. It provides more flexibility to your code since you can have as many arguments as you wish in the future.

Example

def func(*args):
    for arg in args:
        print(arg)
    func(11,22,33,"Django","Python")
list = [11,22,33,"Django","Python"]

func(list)
#OUTPUT
11
22
33
Django
Python

#List
[11, 22, 33, 'Django', 'Python']

What are Kwargs?

**kwargs is a dictionary of keyword arguments. The double asterisk (**) symbol allows us to pass any number of arguments. A keyword argument is usually a dictionary.

Here an example of a keyword argument is fun(a=1,b=17).

Tips

**kwargs are similar to *args, except you declare the variables and the amount within the same function arguments.

Use of Args and Kwargs

Args and kwargs are handy when you need to:

  • Pass multiple arguments in functions
  • Reduce code writing
  • Make your code more readable
  • Reuse the piece of code

Using Both Args and Kwargs in a Function

When using both args and kwargs in the same function definition, *args must occur before **kwargs.

def __init__(self, *args, **kwargs):

Reference