Accepting Unlimited Arguments
Sometimes you don't know ahead of time how many items a user will pass into your function. For example, Python's built-in print() function can take 1 item, 5 items, or 100 items! You can create your own flexible functions using *args and **kwargs.
Positional Arguments (*args)
Adding an asterisk * before a parameter name gathers extra items into a Tuple:
def add_all(*numbers):
# 'numbers' becomes a tuple of whatever items were passed
return sum(numbers)
print(add_all(10, 20)) # Output: 30
print(add_all(5, 10, 15, 20)) # Output: 50
Keyword Arguments (**kwargs)
Adding two asterisks ** before a parameter name gathers named keyword items into a Dictionary:
def print_profile(**user_data):
for key, value in user_data.items():
print(f"{key}: {value}")
print_profile(name="Alice", role="Admin", country="India")
The Correct Order of Parameters
If your function uses regular inputs, default inputs, *args, and **kwargs all together, you must write them in this specific order:
def setup_user(standard_arg, default_arg="OK", *args, **kwargs):
pass
- Standard inputs (
standard_arg) - Default inputs (
default_arg="OK") *args**kwargs
Common Beginner Mistakes
- Order of
*argsand**kwargs:**kwargsmust always be placed at the very end of the parameter list (def fn(*args, **kwargs):). Reversing them raisesSyntaxError.
Quick Summary
*args(Variable Positional Arguments): Captures any number of positional arguments into atuple.**kwargs(Variable Keyword Arguments): Captures any number of named key-value arguments into adict.- Parameter Ordering:
def func(positional, *args, default="val", **kwargs):. - Argument Spreading: Use
*and**during function calls to unpack lists and dicts into arguments.
What's Next?
Let's explore one-line shortcut functions called lambdas and recursive self-calling functions in the next lesson!