/  Technology   /  Python   /  What do these words mean in python: *args, **kwargs? And why would we use it?
Python-Interview-Questions-and-Answers(i2tutorials.com)

What do these words mean in python: *args, **kwargs? And why would we use it?

*args

The *args keyword in python is used to pass a variable number of arguments to a function. It is mainly used to pass a non-keyworded, variable length argument list. The *args keyword allows you to take more arguments than the number of formal arguments which were previously defined by you. By this keyword, any number of extra arguments can be tacked on to your current formal parameters.

Example: 

If we want to make a multiply function that takes any number of arguments and be able to multiply them all, *args can be used to do this.

The * is used with a variable so that it becomes iterative and can do things like iterate over it, run some higher order functions such as map and filter etc.

# Python program to illustrate *args

def test_var_args(f_arg, *argv):

    print "first normal arg:", f_arg

    for arg in argv:

        print "another arg through *argv :", arg



test_var_args('Rahul','python','eggs','test')

This produces the following result:

first normal arg: Rahul

another arg through *argv : python

another arg through *argv : eggs

another arg through *argv : test

**kwargs

**kwargs enables you to pass keyworded variable length of arguments to a function. The keyword kwargs is used with the double star because it allows us to pass through any number of keyword arguments. A keyword argument is something where you provide a name to the variable while passing it into the function.

# Python program to illustrate **kwargs

def greet_me(**kwargs):

    if kwargs is not None:

        for key, value in kwargs.iteritems():

            print "%s == %s" %(key,value)

 >>> greet_me(name="Rahul")

name == Rahul

Leave a comment