Introduction

In this article we will discuss about what is the difference between args and kwargs and how we can use them in python. In Python, args and kwargs are used in function definitions to handle a variable number of arguments, but they differ in the way they handle those arguments.

What is args?

def print_numbers(*args):
    for arg in args:
        print(arg)

print_numbers(1, 2, 3)  # OP: 1 2 3
print_numbers(4, 5, 6, 7)  # OP: 4 5 6 7

What is kwargs?

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

print_info(name="Loki", age=25)
# Output:
# name: Loki
# age: 25

print_info(city="Noida", country="India", population=850000)
# Output:
# city: Noida
# country: India
# population: 850000

You can also use args and kwargs together in a function definition to allow the function to accept both positional and keyword arguments simultaneously.

def greeting(name, *args, greeting="Hello", **kwargs):
    print(f"{greeting}, {name}")
    print("Args:", args)
    print("Kwargs:", kwargs)

greeting("Loki", 25, "Data", job="Engineer")
# Output:
# Hello, Loki
# Args: (25, 'Data')
# Kwargs: {'job': 'Engineer'}

In the above example, the greeting function accepts a required positional argument name, any number of additional positional arguments *args, a keyword argument greeting with a default value, and any number of additional keyword arguments **kwargs.

Summary

*args is used to handle a variable number of non-keyworded (positional) arguments, while **kwargs is used to handle a variable number of keyworded (named) arguments. These constructs provide flexibility and versatility in function definitions, allowing you to write more reusable and adaptable code.