Amazon Interview Questions | Difference between *args and **kwargs
Question
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
It will take less than 1 minute to register for lifetime. Bonus Tip - We don't send OTP to your email id Make Sure to use your own email id for free books and giveaways
Answers ( 3 )
*args and **kwargs are used when you are not sure how many arguments
are going to be passed to your function.
The syntax is * and ** but the names *args and **kwargs are used only by
convention and there is no hard and fast requirement to use them.
1) *args
Using the *, the variable that we associate with the * becomes an iterable ,that means
you can do things like iterate over it, run some higher order functions such as map and filter, etc.
It can also be used in combination with your formal parameters.After the formal parameters
have exhausted, the rest of the parameters are associated with *args.
Example :
def someFunc(*args):
for arg in args:
print (arg)
someFunc(‘Hi’, ‘This’, ‘is’, ‘DataMonk’)
OUTPUT:
Hi
This
is
DataMonk
2) **kwargs in function definitions in python is used to pass a key-value pairs,
variable-length argument list. Basically, like a Dictionary.
def openers(**kwargs):
for name, value in kwargs.items():
print( ‘{0} = {1}’.format(name, value))
openers(Shikhar = ‘Rohit’, Roy = ‘Bairstow’)
Shikhar = Rohit
Roy = Bairstow
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.
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 (and any number of them).
If you do not know how many arguments that will passed into a function, add a * before parameter name.
Eg- def my_function(*kids):
print(“The younger is “ + kids[2])
my_function(“Emil”, “Tobias”, “Lima”)
Output- The youngest is Lima.
If you do not know how many keyword arguments will pass, add two asterisk **
Eg- def my_function(**kid):
print(“His last name is “ + kid[“lname”])
my_function(fname= “Tobias”, lname= “refs”)
Output- His last name is refs.
Also Args receives list and kwargs receives dict.