OneCompiler

*args and **kwargs explained in Python

227


In this post, we will learn about *args and **kwargs

These are used to send variable-length parameters to a function.

1. *args

This is used to pass a variable number of arguments to a function.

Example

def display (*p):
  for i in p:
    print(i)
  
display(1,2,3)

This will output,

1
2
3

Here, we sent 3 variables to a display() function, with the help of *args syntax, we can use the input as a list and perform tasks.

2. **kwargs

This is used to send variable length keyword arguments to a function.

Example

def display (**p):
  for i,j in p.items():
    print(i,"-",j)
  
display(a=1,b=2)

This will output,

a - 1
b - 2

We sent keyword arguments to the display() function, with the help of **kwargs syntax, the function will read the input as a dictionary and can perform tasks.

Check Output here