Advanced Functions
*args, **kwargs, lambdas, and decorators
Beyond Basic Functions
You've written functions with fixed parameters. Now let's make them flexible — handling any number of arguments and even modifying other functions.
*args — Variable Positional Arguments
*args lets a function accept any number of positional arguments:
*args in Action
**kwargs — Variable Keyword Arguments
**kwargs captures named arguments into a dictionary:
**kwargs in Action
All Together: order_pizza()
Check Your Understanding
What type is *args inside a function?
Lambda Functions — Anonymous One-Liners
A lambda is a small, unnamed function defined in a single expression:
Lambda Functions
Lambda rule of thumb: Use them for simple operations you'd write in one line. For anything complex, write a regular function with a name.
Decorators — Functions That Modify Functions
A decorator wraps a function, adding behavior before and/or after it runs:
A Timer Decorator
A Retry Decorator
Check Your Understanding
What does @timer above a function definition do?
Exercise
Write a function merge_dicts(*dicts) that takes any number of dictionaries using *args and merges them into one. If the same key appears in multiple dicts, later values should win. Then write a lambda-based one-liner that takes a list of words and returns only words longer than 4 characters, sorted alphabetically.
Key Takeaways
*argscaptures any number of positional arguments as a tuple**kwargscaptures named arguments as a dictionary- Lambda functions are anonymous one-liners:
lambda x: expr - Decorators wrap functions to add behavior (
@decorator) - These features make Python code more flexible and expressive
- Use them sparingly — readable code beats clever code