*args and **kwargs in Python
What do you mean by *args and **kwargs in Python function?
*args:
- *args is a special syntax used in the function definition to pass variable-length arguments.
- “*” means variable length and “args” is the name used by convention. You can use any other.
**kwargs:
- **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
- Here, also, “kwargs” is used just by convention. You can use any other name.
- Keyworded argument means a variable that has a name when passed to a function.
- It is actually a dictionary of the variable names and its value.
=========================================================================
Important Points related to *args & **kwargs:
- *args and **kwargs are special keyword which allows function to take variable length argument.
- *args passes variable number of non-keyworded arguments list and on which operation of the list can be performed.
- **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.
- *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)
Comments
Post a Comment