what is the use of args and kwargs in python code example
Example 1: variable number of arguments to python class
def multiply(*args):
z = 1
for num in args:
z *= num
print(z)
multiply(4, 5)
multiply(10, 9)
multiply(2, 3, 4)
multiply(3, 5, 10, 6)
Example 2: **kwargs
When it iterating over a dictionary you are only able to iterate over
the keys not the values. The ** when placed before a variable will allow
you to iterate and unpack both key and value pairs. Because you are
unpacking both key and value this will return the result as a dictionary.
Example 3: python *arg **kwargs
>>> def f(a, b, *args, **kwargs):
... print(F'a = {a}')
... print(F'b = {b}')
... print(F'args = {args}')
... print(F'kwargs = {kwargs}')
...
>>> f(1, 2, 'foo', 'bar', 'baz', 'qux', x=100, y=200, z=300)
a = 1
b = 2
args = ('foo', 'bar', 'baz', 'qux')
kwargs = {'x': 100, 'y': 200, 'z': 300}