Computer >> Computer tutorials >  >> Programming >> Python

How to use *args and **kwargs in Python?


In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is seen that the asterisk (*) is important here, and along with the word args it means there is a variable length list of non-keyworded arguments.

Example

 Given code on *args is rewritten as follows

def multiply(*args):
    y = 1
    for i in args:
        y = y * i
    print y
multiply(3, 4)
multiply(10, 8)
multiply(2, 5, 6)
multiply(4, 5, 10, 9)

Output

C:/Users/TutorialsPoint1/~.py
12
80
60
1800

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks (**) are the important and along with the word kwargs, indicate that there is a dictionary of variable-length keyworded arguments.

Example

Given code on **kwargs is rewritten as

def print_kwargs(**kwargs):
    print(kwargs)
print_kwargs(a='foo', b=10, c =True)

Output

C:/Users/TutorialsPoint1/~.py
{'a': 'foo', 'b': 10, 'c': True}