DEV Community

Avinash
Avinash

Posted on • Edited on

1 1

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay