xplain the difference between *args and **kwargs.
Both *args
and **kwargs
allow functions to accept a variable number of arguments, but they serve different purposes:
Feature | *args | **kwargs |
---|---|---|
Purpose | Accepts positional arguments as a tuple | Accepts keyword arguments as a dictionary |
Syntax | Single asterisk (*args ) | Double asterisk (**kwargs ) |
Use Case | When you don’t know how many positional arguments will be passed | When you don’t know how many keyword arguments will be passed |
Example | def func(*args): | def func(**kwargs): |
1. *args
(Variable-Length Positional Arguments)
Collects extra positional arguments into a tuple.
Useful when the number of arguments is unknown.
Example:
def sum_numbers(*args): total = 0 for num in args: total += num return total print(sum_numbers(1, 2, 3)) # Output: 6 print(sum_numbers(10, 20)) # Output: 30
How It Works:
sum_numbers(1, 2, 3)
→args = (1, 2, 3)
sum_numbers(10, 20)
→args = (10, 20)
2. **kwargs
(Variable-Length Keyword Arguments)
Collects extra keyword arguments into a dictionary.
Useful when passing named arguments dynamically.
Example:
def print_user_details(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_user_details(name="Alice", age=25, city="New York")
Output:
name: Alice age: 25 city: New York
How It Works:
print_user_details(name="Alice", age=25)
→kwargs = {"name": "Alice", "age": 25}
Combining *args
and **kwargs
You can use both in the same function:
def example_function(arg1, *args, **kwargs): print(f"First argument: {arg1}") print(f"Additional positional args: {args}") print(f"Keyword args: {kwargs}") example_function(10, 20, 30, name="Alice", age=25)
Output:
First argument: 10 Additional positional args: (20, 30) Keyword args: {'name': 'Alice', 'age': 25}
Key Takeaways
*args
→ Handles extra positional arguments (stored as a tuple).**kwargs
→ Handles extra keyword arguments (stored as a dictionary).Both make functions flexible for different input scenarios.
They are often used in decorators, inheritance, and dynamic function calls.
Would you like a practical example (e.g., building a dynamic SQL query)?