Appearance
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:
*Pass a non-keyworded, variable-length argument list to a function in Python using args
python
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
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
**kwargs is used to pass a keyworded, variable-length argument list to a function. For example:
**Pass a keyworded, variable-length argument list to a function in Python using kwargs
python
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 = 3Both *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:
**Use *args and kwargs in one function in Python
python
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:
console
1
2
3
name = Alice
age = 20