Skip to main content
Python provides powerful ways to handle function arguments flexibly. Beyond standard positional and keyword arguments, you can work with variable-length inputs, enforce how arguments are passed, and control parameters precisely.

Variable-length arguments (*args)

When you want a function to accept any number of positional arguments, prefix a parameter name with a single asterisk *. By convention, we use *args. Within the function, args is a tuple containing all the positional arguments passed.
Precaution: You can only have one *args parameter in a function definition. Standard positional arguments should come before *args.

Variable keyword arguments (**kwargs)

To accept any number of keyword arguments, prefix a parameter name with a double asterisk **. By convention, we use **kwargs. Within the function, kwargs is a dictionary mapping the parameter names to their values.
*args collects positional arguments as a tuple, while **kwargs collects keyword arguments as a dictionary.

Mixing *args and **kwargs

You can use standard arguments, *args, and **kwargs in the same function.
Important Order Rule: The order of parameters in the function definition must be:
  1. Standard positional arguments
  2. *args
  3. Keyword-only arguments (with or without defaults)
  4. **kwargs
Mixing this order will result in a SyntaxError.

Positional-only parameters (/)

Introduced in Python 3.8, the forward slash / indicates that the parameters before it must be passed as positional arguments, and cannot be passed as keyword arguments.

Keyword-only parameters (*)

To enforce that certain parameters can only be passed as keyword arguments, place an asterisk * in the parameter list. Every parameter after the * must be passed as a keyword argument.

What’s next?

Now let’s learn how nested functions work, how variable scopes are resolved via the LEGB rule, and how to use the global and nonlocal keywords!

Scopes & Nested Functions

Learn about nested functions and variable scopes