Use of *args and **kwargs
In Python, *args
and **kwargs
are special keywords that allow you to pass a variable number of arguments to a function.
*args
is used to pass a non-keyworded, variable-length argument list to a function. For example:
def print_args(*args):
for arg in args:
print(arg)
print_args(1, 2, 3) # prints 1, 2, 3
print_args("a", "b", "c") # prints a, b, c
Watch a video course
Python - The Practical Guide
**kwargs
is used to pass a keyworded, variable-length argument list to a function. For example:
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
print_kwargs(name="Alice", age=20) # prints name = Alice, age = 20
print_kwargs(a=1, b=2, c=3) # prints a = 1, b = 2, c = 3
Both *args
and **kwargs
can be used to pass arguments to a function in a flexible way, allowing you to pass a varying number of arguments to a function.
You can also use both *args
and **kwargs
in the same function definition, but *args
must come before **kwargs
.
For example:
def print_args_and_kwargs(*args, **kwargs):
for arg in args:
print(arg)
for key, value in kwargs.items():
print(f"{key} = {value}")
print_args_and_kwargs(1, 2, 3, name="Alice", age=20)
This would print:
1 2 3 name = Alice age = 20