W3docs

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

In Python, the double star (**) is used to denote an "unpacking" operator, which allows you to unpack a dictionary or other iterable data type into keyword arguments in a function call.

In Python, the double star (**) is used to denote an "unpacking" operator, which allows you to unpack a dictionary or other iterable data type into keyword arguments in a function call. For example, consider the following function:

A simple function in Python

python— editable, runs on the server

This function takes two arguments: greeting and recipient. If we have a dictionary that contains these values, we can "unpack" them into the function call like this:

Unpack a dictionary's values using a double asterisk and pass them to a function in Python

python— editable, runs on the server

This would return the string "Hello, world!".

The single star (*) is used to unpack a sequence (such as a list or tuple) into individual positional arguments in a function call. For example:

Unpack a sequence into individual arguments in a function call in Python

python— editable, runs on the server

This would print the following:

Hello, World!

Using * and ** in function definitions

While * and ** unpack arguments when calling a function, they pack arguments when defining a function. This allows functions to accept a variable number of arguments:

  • *args packs extra positional arguments into a tuple.
  • **kwargs packs extra keyword arguments into a dictionary.

For example:

python— editable, runs on the server

This flexibility makes * and ** essential for writing adaptable Python functions.