4.10 Keyword Arguments

When calling functions, you can use keyword arguments to pass arguments in any order. To demonstrate keyword arguments, we redefine the rectangle_area function—this time without default parameter values:


In [1]: def rectangle_area(length, width):
   ...:     """Return a rectangle's area."""
   ...:     return length * width
   ...:

Each keyword argument in a call has the form parametername = value. The following call shows that the order of keyword arguments does not matter—they do not need to match the corresponding parameters’ positions in the function definition:


In [2]: rectangle_area(width=5, length=10)
Out[3]: 50

In each function call, you must place keyword arguments after a function’s positional arguments—that is, any arguments for which you do not specify the parameter name. Such arguments are assigned to the function’s parameters left-to-right, based on the argument’s positions in the argument list. Keyword arguments are also helpful for improving the readability of function calls, especially for functions with many arguments.

Self Check

  1. (True/False) You must pass keyword arguments in the same order as their corresponding parameters in the function definition’s parameter list.
    Answer: False. The order of keyword arguments does not matter.