Amazon Interview Questions | Difference between *args and **kwargs

Question

With example

in progress 0
TheDataMonk 4 years 3 Answers 1366 views Grand Master 0

Answers ( 3 )

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

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

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

Leave an answer

Browse
Browse