*args and **kwargs in Python

*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:

print (i)

myFun('Hello', 'My', 'Name', .''is, 'Prabin')

Output: <class ‘tuple’> || Hello || My || Name || is || Prabin

def myFun(arg1, *argv):

print ("First argument :", arg1)

for arg in argv:

print(arg)

myFun('Hello', 'My', 'Name', .''is, 'Prabin')

Output: First argument : Hello || My || Name ||is || Prabin

**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

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).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store