In Python, *args
and **kwargs
are special syntax used in function definitions to allow for variable-length arguments. Here’s the detailed difference:
1. *args
(Non-Keyword Arguments)
- Purpose:
*args
is used to pass a variable number of positional arguments to a function. - How it Works: Inside the function,
*args
is treated as a tuple containing all the additional positional arguments passed.
Example:
def example_function(*args):
for arg in args:
print(arg)
example_function(1, 2, 3, 4)
# Output:
# 1
# 2
# 3
# 4
- Key Points:
- Use
*args
when the number of arguments is unknown and you don’t need to associate names with values. - It collects all extra positional arguments into a tuple.
- Use
2. **kwargs
(Keyword Arguments)
- Purpose:
**kwargs
is used to pass a variable number of keyword arguments (name-value pairs) to a function. - How it Works: Inside the function,
**kwargs
is treated as a dictionary containing all the additional keyword arguments passed.
Example:
def example_function(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
example_function(a=1, b=2, c=3)
# Output:
# a = 1
# b = 2
# c = 3
- Key Points:
- Use
**kwargs
when you need to handle named arguments that you may not know in advance. - It collects all extra keyword arguments into a dictionary.
- Use
3. Using *args
and **kwargs
Together
- Order: If you use both
*args
and**kwargs
in the same function definition,*args
must appear before**kwargs
.
Example:
def example_function(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
example_function(1, 2, 3, a=4, b=5)
# Output:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'a': 4, 'b': 5}
4. Practical Use Case
When the exact number and type of arguments are unknown:
*args
can capture extra positional arguments.**kwargs
can capture extra named arguments.
def greet(*args, **kwargs):
for name in args:
print(f"Hello, {name}!")
for key, value in kwargs.items():
print(f"{key}: {value}")
greet("Alice", "Bob", age=30, location="New York")
# Output:
# Hello, Alice!
# Hello, Bob!
# age: 30
# location: New York
5. Summary
Feature | *args | **kwargs |
---|---|---|
Purpose | Handles extra positional arguments | Handles extra keyword arguments |
Data Type | Tuple | Dictionary |
Use Case | For a variable number of arguments without names | For a variable number of arguments with names |
Example Input | function(1, 2, 3) | function(a=1, b=2, c=3) |
By combining *args
and **kwargs
, you can write functions that are highly flexible and capable of handling a wide range of inputs.