We're making some improvements. Some features may be temporarily unavailable.
intermediate20 min

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

Output
Run your code to see output here

**kwargs — Variable Keyword Arguments

**kwargs captures named arguments into a dictionary:

**kwargs in Action

Output
Run your code to see output here

All Together: order_pizza()

Output
Run your code to see output here

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

Output
Run your code to see output here

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

Output
Run your code to see output here

A Retry Decorator

Output
Run your code to see output here

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.

Python will load on first run

Key Takeaways

  • *args captures any number of positional arguments as a tuple
  • **kwargs captures 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

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...