DEV Community

Avinash
Avinash

Posted on • Updated on

args and kwargs in python


*args in Python

*args are best used when we want to pass list of arguments.
Basic usage

 def listOfValues(*args):
      print(args)
listOfValues(1,2,3)
Enter fullscreen mode Exit fullscreen mode

the output will be (1,2,3)

print(args) will print a tuple of all the arguments that we are passing in when calling the function.

Example 2 passing list or dictionary

 def iterable(*args):
      print(args)
iterable([1,2,4,5])

Enter fullscreen mode Exit fullscreen mode

this will print a tuple of list. Something like this ([1,2,3,4,5],)

Note: If you are familiar with ES6 rest operator. *args works a lot similar rest operator in ES6.


**kwargs in Python

**Kwargs accepts named arguments instead of positional arguments. When we use **Kwargs in parameter and try to print the values we get a dictionary.

   def getValues(**kwargs):
       print(kwargs)
   getValues(a=1,b=2)
Enter fullscreen mode Exit fullscreen mode

The output is going to be {"a":1,"b":2}

another example where we use **kwargs for adding numbers

   def add(**kwargs):
    res = 0
    for k in kwargs.values():
        res+=k
    print(res)


add(a=1,b=2, c=3)
Enter fullscreen mode Exit fullscreen mode

Output is 6

Note:- The order of parameters has to be in the exact order
1. Standard arguments
2. *args arguments
3. **kwargs arguments

Discussion (0)