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?
- The *args syntax is used to pass a non-keyword (positional) argument and a variable-length argument list to a function.
- The *args allows you to pass any number of positional arguments to the function.
- Inside the function, args is a tuple containing all the positional arguments passed to the function.
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?
- The **kwargs syntax is used to pass a keyworded (named), variable-length argument list to a function.
- The **kwargs allows you to pass any number of keyword arguments to the function.
- Inside the function, kwargs is a dictionary containing all the keyword arguments passed to the function, where the keys are the argument names, and the values are the argument values.
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.