Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Functions & functional toolsJuniorCommonPractical

How do `*` and `**` unpack a collection into a function call, and can they be combined?

Answer

At a call site, `*iterable` unpacks each element of a list, tuple or other iterable into a separate positional argument, and `**mapping` unpacks each key-value pair of a dict into a separate keyword argument, matched by parameter name. Both can be combined in a single call, and multiple starred arguments can even be merged from different sources, as long as the resulting set of positional and keyword arguments is one the target function actually accepts.

Strong answer includes

  • * unpacks an iterable into positional arguments
  • ** unpacks a mapping into keyword arguments matched by name
  • both can be combined and merged from multiple sources

Practical example

Python example
args = (2, 3); kwargs = {"base": 10}; pow(*args, **kwargs)

calls

Python example
pow(2, 3, base=10)

-style unpacking, spreading the tuple as positional arguments and the dict as keyword arguments.

#functions#unpacking

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics