Python – *args and **kwargs

Sometimes you do not know how many parameters are required, how many arguments are required and you might need variable length of argument, where you can pass it in number of arguments because you don’t know how many arguments will be needed. So to process a function for more arguments than you have specified while defining the function, you can use variable length arguments.

To handle such cases you have star operator (*).

There are two special symbols in python for passing arguments:

  1. *args – Non-keyword Arguments
  2. **kwargs – Keyword Arguments

*args

args allows your function to accept an unspecified arbitrary amount of arguments. In some situation, you don’t know beforehand how many arguments your function should take so there are cases where you want to be a little flexibility in that sense astrick (*) args allows you to do that.

args is actually not a keyword but this is a sort of placeholder and can be replaced by any other word.

for example:

def info(user, *users):
    print("Users of Python: ")
    print(user)

    for usr in users:
        print("Users in Python: ", usr)

# info("Annie")
info('Annie', "Dave", "John", "Mark", "Peter")

#OUTPUT
Users of Python:
Annie
Users in Python:  Dave
Users in Python:  John
Users in Python:  Mark
Users in Python:  Peter

**Kwargs

kwargs allows your function to accept an unspecified arbitrary amount of keyworded arguments. kwargs is used with double astricks (**). The reason is because the double astrick allows you to pass through keyworded arguments.

def myFunction(arg1, arg2, arg3, *args, **kwargs):
    print('First Normal Argument :' + str(arg1))
    print('Second Normal Argument :' + str(arg2))
    print('Third Normal Argument :' + str(arg3))
    print('Non-keyworded Argument :' + str(args))
    print('Keyworded Argument :' + str(kwargs))


myFunction(1,2,3,4,5,6,7,name='Mark', country='India', age=25)

#OUTPUT
First Normal Argument :1
Second Normal Argument :2
Third Normal Argument :3
Non-keyworded Argument :(4, 5, 6, 7)
Keyworded Argument :{'name': 'Mark', 'country': 'India', 'age': 25}
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial