Contenido del Curso
Mastering Python: Annotations, Errors and Environment
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
ortuple
to a function, you can unpack it using the asterisk (*
) before thelist
ortuple
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 (**
) beforedict
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!
¿Todo estuvo claro?