*args and **kwargs in Python
--
Most interview asked question is what is the differences between *args and **kwargs and how you can used these in your code.
*arg:
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.
Example for usage of *arg:
def
myFun(*argv):
print(type(argv))
for
i in
argv:
(i)
myFun('Hello', 'My', 'Name', .''is, 'Prabin')
Output: <class ‘tuple’> || Hello || My || Name ||
is || Prabin
def
myFun(arg1, *argv):
("First argument :", arg1)
for
arg in
argv:
print(arg)
myFun('Hello', 'My', 'Name', .''is, 'Prabin')
Output: First argument : Hello || My || Name ||is || Prabin
With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
**kwargs
The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments
Example for usage of **kwargs:
def myFun(**kwargs):
print(type(kwargs))
for key, value in kwargs.items():
print (“%s == %s” %(key, value))myFun(first =’Prabin’, last=’Karki’)
Output: <class ‘dict’> || first == Prabin ||
last == Karki
A keyword argument is where you provide a name to the variable as you pass it into the function.
Using *args and **kwargs in same line to call a function
def myFun(arg1, *args,**kwargs):
print (“First argument :”,arg1)
print(“args: “,args)
print(“kwargs: “,kwargs)
myFun(“Learn”,”Share”,”and”, “Grow”, first=”Prabin”, last=”Karki”)
Output: First argument : Learn || args: (‘Share’, ‘and’, ‘Grow’) || kwargs: {‘first’: ‘Prabin’, ‘last’: ‘Karki’}
Thank you so much (Learn Grow & Share).