How to pass arguments in Python

In Python, we can use two special symbols for passing arguments to a function;
*args
(Non-Keyword Arguments), **kwargs
(Keyword Arguments)
We use *args and **kwargs as an argument when we have no doubt about the number of arguments we should pass in a function.
*args
The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments). Using the *, the variable that we associate with the * becomes an iterable meaning you can do things like iterate over it, run some higher-order functions such as map and filter, etc.
def func(*argv): for i in argv: print(i) func('python', 1, 'red', 2)
Output:
python 1 red 2
**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 that the double star allows us to pass through keyword arguments. (A keyword argument is where you provide a name to the variable as you pass it into the function.)
One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out.
def func(**kwargs): for key, value in kwargs.items(): print("{} - {}".format(key, value)) func(lang='python', num=1, color='red')
Output:
lang - python num - 1 color - red