“*args” and “**kwargs” in Python
Knowing about the “*args” and “**kwargs” functional parameters in Python
In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols:
- *args stands for arguments.
2) **kwargs stands for keyword arguments.
We use *args and **kwargs as an argument when we are unsure about the number of arguments to pass in the functions.
>>> def func1(n1,n2):
return sum((n1,n2))>>> func1(2,4)
6
Now if I pass 3 arguments then we will have to change the function so it can take 3 arguments. Now instead of this, in cases where we are unaware of the number of arguments that will be passed, we can use args or kwargs.
args
It generates a tuple of values.
>>> def func1(*args):
return sum(args)>>> func1(1,2,3)
6
Notice when we print args, we get a tuple.
>>> def func1(*args):
print(args)
return sum(args)>>> func1(3,4,5,6,7,8)
(3, 4, 5, 6, 7, 8)
33
Typically args is a tuple and it takes in any number and performs the function. args is just a keyword and can be changed, the * sign is important.
>>> def func1(*pizza):
return sum(pizza)>>> func1(1,2)
3>>> def func2(*args):
for i in args:
print(i)>>> func2(1,2,3,4,5)1
2
3
4
5
kwargs
It generates a dictionary of key-value pairs.
>>> def func3(**kwargs):
if 'coding' in kwargs:
print("My favorite language is{}".format(kwargs['coding']))
else:
print("fail")>>> func3(coding='python')
My favorite language is python
Now if we put more arguments while calling even though it is not mentioned in the function, it would not raise errors.
>>> func3(coding='python', editor='sublime')
My favorite language is python
Notice when we print kwargs, we get a dictionary.
>>> def func3(**kwargs):
print(kwargs)
if 'coding' in kwargs:
print("My favorite language is {}".format(kwargs['coding']))
else:
print("fail")>>> func3(coding='python', editor='sublime')
{'coding': 'python', 'editor': 'sublime'}
My favorite language is python
Again kwargs is just a keyword, the ** sign is important.
>>> def func3(**pizza):
print(pizza)
if 'coding' in pizza:
print("My favorite language is {}".format(pizza['coding']))
else:
print("fail")>>> func3(coding='python', editor='sublime')
{'coding': 'python', 'editor': 'sublime'}
My favorite language is python
Combination of args and kwargs
>>> def func4(*args, **kwargs):
print(args)
print(kwargs)
print("I would love {} {}". format(args[0], kwargs['objects']))>>> func4(4,2,3, objects="pencils", coding="python")
(4, 2, 3)
{'objects': 'pencils', 'coding': 'python'}
I would love 4 pencils
Refer to the notebook here.
Beginner-level books to refer to learn Python:
Advance-level books to refer to learn Python:
Reach out to me: LinkedIn
Check out my other work: GitHub