Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

In following code

def multiply(*args)
     y =1
     …
multiply(3,4)
and
def print_kwargs(**kwargs)
      print (kwargs)
print_kwargs(a=’foo’, b=5, c=True)

How do I use the *args (here 3, 4) to multiply?       and

How do I use the **kwargs (here a=’foo’, b=5, c=True)?


1 Answer
Rajendra Dharmkar

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.

 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.

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}
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.