Python Argument Unpacking
Learn how to unpack iterables and mappings into function calls with * and **, how unpacking differs from collecting arguments, and how Python handles multiple unpackings.
Intermediate
Python can unpack a collection at the moment you call a function.
* supplies positional arguments from an iterable, while
** supplies keyword arguments from a mapping. This is the caller-side counterpart to the
*args and
**kwargs parameter forms already taught in Function Parameter Kinds.
Unpack an iterable into positional arguments
Place
* before an iterable in a function call. Python expands its items as separate positional arguments.
|
|
The two tuple items become the two positional arguments x and y.
Unpack a mapping into keyword arguments
Place
** before a mapping in a function call. Its string keys are matched to parameters by name.
|
|
The mapping provides named arguments, so the call does not repeat each key as a separate keyword argument.
Combine explicit arguments and unpacking
A call can combine ordinary positional arguments,
*iterable, ordinary keyword arguments, and
**mapping when the resulting arguments satisfy the function signature.
|
|
The explicit scheme is followed by two positional values from parts, then the secure keyword comes from options.
Multiple iterable unpackings
A function call can contain more than one
* unpacking. Python treats the produced items as additional positional arguments in the call.
|
|
Each iterable contributes its items, producing the four positional arguments expected by show().
Multiple mapping unpackings
A call can also contain multiple
** mappings. Each mapping supplies additional keyword arguments; a parameter must not receive two values.
|
|
The mappings are combined for the call because they provide different parameter names.
The value must have the right kind
The operand after
* must be iterable. The operand after
** must be a mapping whose keys are strings for a function call. If unpacking supplies an argument that conflicts with another value, Python raises a
TypeError.
|
|
Both calls pass the same two values, but one uses positional unpacking and the other uses keyword unpacking.
Use unpacking when the data is already grouped
Argument unpacking is most useful when a list, tuple, or mapping already represents the arguments you need to pass. It avoids manually copying each value into a call and keeps the connection between the data structure and the function signature visible.
|
|
The tuple already contains the two values needed by the function, so unpacking makes the call direct and readable.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.