*args vs **kwargs
In Python programming, *args and **kwargs are special syntaxes used in function definitions to allow a variable number of arguments to be passed to a function.
*args (Non-keyword Arguments):
- The
*argsparameter allows a function to accept any number of non-keyword arguments. - The
*beforeargstells Python to unpack the arguments passed to the function and store them in a tuple namedargs. - You can name the parameter
*argsanything you like, but the*symbol is necessary to indicate variable-length arguments. - Example:
def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3) # Prints: 1 2 3
my_function('Hello', 'World') # Prints: Hello World**kwargs (Keyword Arguments):
- The
**kwargsparameter allows a function to accept any number of keyword arguments, which are typically specified as key-value pairs. - The
**beforekwargstells Python to unpack the keyword arguments passed to the function and store them in a dictionary namedkwargs. - Similar to
*args, you can choose any name for the parameter, but the**symbol is required. - Example:
def my_function(**kwargs):
for key, value in kwargs.items():
print(key, value)
my_function(name='Alice', age=25) # Prints: name Alice, age 25
my_function(city='New York', country='USA') # Prints: city New York, country USA*args and **kwargs together in a function definition:
It’s worth noting that you can use *args and **kwargs together in a function definition. In such cases, *args captures non-keyword arguments, while **kwargs captures keyword arguments.
def print_arguments(*args, **kwargs):
for arg in args:
print("Positional argument:", arg)
for key, value in kwargs.items():
print("Keyword argument -", key + ":", value)
print_arguments(1, 2, 3, name='Alice', age=25)In this example, the print_arguments function accepts a variable number of positional arguments using *args and a variable number of keyword arguments using **kwargs. It then iterates over the positional arguments and prints each one, and also iterates over the keyword arguments and prints the key-value pairs.
Positional argument: 1
Positional argument: 2
Positional argument: 3
Keyword argument - name: Alice
Keyword argument - age: 25