Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Unpacking | Function Arguments in Details
Mastering Python: Annotations, Errors and Environment
course content

Course Content

Mastering Python: Annotations, Errors and Environment

Unpacking

Unpacking is the process of extracting data from a collection, such as a list or a tuple, and assigning it to individual variables. It is called unpacking because the data is taken apart and assigned to separate variables as if it were a package that was being unpacked.

In the example above, we unpacked the values in the list lst into separate variables a, b, and c.

Although this is simple, it is very important to know and is frequently used in real development and frameworks.

Arguments Unpacking

Let's consider a scenario where we have a list of arguments that we need to pass to a function, such as the multiply function:

If we pass the arguments list to the multiply function, the list will be the only argument passed.

The arguments list was passed as a single argument.

To resolve this problem, we can unpack the arguments list when passing it to the function.

Note

To pass arguments from a list or tuple to a function, you can unpack it using the asterisk (*) before the list or tuple name. For example, *list_name.

Run the following code:

Now, the program is working correctly.

Keyword Arguments Unpacking

Let's consider another case where you have a function named snakes that takes **kwargs:

You know that kwargs is a dict. Assume you take the key_value dictionary from another program:

The above example shows that a regular argument passing does not provide the expected result.

To pass the key_value as kwargs for snakes, you need to unpack it similarly to the first case.

Note

To pass arguments from dict to the function, you need to unpack it using the two asterisk (**) before dict name. For example, **dict_name.

Now, let's check it:

Let's take a look at different representations to gain a better understanding:

Great! Now you can use unpacking in your program!

Everything was clear?

Section 2. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt