Jan 05, 2020

What is meaning of and usage of *args, **kwargs in Python?

*args: Used when not sure the number of arguments to be passed to a function. e.g. to pass a stored list or tuple of arguments


def show_args(*args):  
    for arg in args:  
        print (arg) 
    
show_args('Hello', 'World', 'Python')  

Output:


Hello
World
Python

**kwargs: Used when not sure the number of keyword arguments to be passed to a function. e.g. to pass the values of a dictionary as keyword arguments


def show_kwargs(**kwargs):  
    for key, value in kwargs.items(): 
        print (f"{key}: {value}")

show_kwargs(first='1', second='2', third='3')

Output:


first: 1
second: 2
third: 3

Enjoy Python!