In Python, functions often need to handle a variable number of arguments. The special symbols *args and **kwargs allow functions to accept an arbitrary number of inputs, making them more flexible and reusable.
These constructs are particularly useful when the exact number of arguments is not known in advance.
*args allows a function to accept any number of positional arguments**kwargs allows a function to accept any number of keyword arguments*args collects extra positional arguments into a tuple.
def function_name(*args):
# code
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(1, 2, 3))
print(add_numbers(5, 10, 15, 20))
Output:
6
50
Here, args behaves like a tuple:
(1, 2, 3)
**kwargs collects extra keyword arguments into a dictionary.
def function_name(**kwargs):
# code
def display_info(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
display_info(name="Alice", age=25, city="Delhi")
Output:
name : Alice
age : 25
city : Delhi
Here, kwargs behaves like:
{'name': 'Alice', 'age': 25, 'city': 'Delhi'}
You can use both in the same function.
def demo(a, *args, **kwargs):
print("a =", a)
print("args =", args)
print("kwargs =", kwargs)
demo(10, 20, 30, name="John", age=22)
Output:
a = 10
args = (20, 30)
kwargs = {'name': 'John', 'age': 22}
When combining different types of parameters, the correct order must be followed:
def func(a, b, *args, **kwargs):
pass
Order:
*args**kwargs| Feature | *args | **kwargs |
|---|---|---|
| Type | Tuple | Dictionary |
| Arguments | Positional | Keyword |
| Usage | Multiple values | Named parameters |
*args and **kwargs are not special keywords—the names can be anything. The important part is the * and ** operators. However, using the conventional names improves readability and is considered best practice.
*args and **kwargs provide powerful mechanisms for handling variable inputs in Python functions. They enhance flexibility, reduce code redundancy, and are widely used in advanced Python programming and real-world applications.