What Are *Args And **Kwargs In Python And How To Use Them?

What Are *Args And **Kwargs In Python And How To Use Them?

Published on October 09 2023

In this tutorial, we will learn about *args and **kwargs in Python with an example and how to use them. This tutorial is part of Python's top 25 most commonly asked interview questions.

*args

  • It is used to pass multiple arguments in a function.
  • We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function.

Example

def fun(*args): 
    pass 
fun(1,2,3,4,5,6) 
# or 
fun(1,2)

**kwargs

  • It is used to pass multiple keyword arguments in a function in Python.
  • **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments.

Example

def fun(**kwargs):
    pass 
    
fun(name=”jack”, age=25)

“args” and “kwargs” is the name used just by convention. You can use any other name.

To know about it, please refer to the official documentation website - official website.