*args and **kwargs in Python

 

What do you mean by *args and **kwargs in Python function?

*args:

  1. *args is a special syntax used in the function definition to pass variable-length arguments.
  2. “*” means variable length and “args” is the name used by convention. You can use any other.

**kwargs:

  1. **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
  2. Here, also, “kwargs” is used just by convention. You can use any other name.
  3. Keyworded argument means a variable that has a name when passed to a function.
  4. It is actually a dictionary of the variable names and its value.
=========================================================================

Important Points related to *args & **kwargs:

  1. *args and **kwargs are special keyword which allows function to take variable length argument.
  2. *args passes variable number of non-keyworded arguments list and on which operation of the list can be performed.
  3. **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.
  4. *args and **kwargs make the function flexible.

Example for *args:

                            def mult(a,b,*c):
                                    mul=a*b
                                    for num in c:
                                        mul=mul*num
                                    return mul
Call the function:
    print(mult(1,2,3,4,5))

Example for *kwargs:
                            def greet(**k):
                                    for key,value in k.items():
                                    print("{} is {}".format(key,value))
Call the function:
greet(Name="VDS TECH LABS",Age=25)

Thanks for reading!!

Comments

Popular posts from this blog

Python namespaces & LEGB rule in Python