Course Content
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.
lst = [11, 22, 33] a, b, c = lst print(lst) print("a =", a) print("b =", b) print("c =", c)
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.
def multiply(*args): print("Args:", args) result = 1 for arg in args: result *= arg return result arguments = [11, 22, 33, 44, 55] print("Result:", multiply(arguments))
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:
def multiply(*args): print("Args:", args) result = 1 for arg in args: result *= arg return result arguments = [11, 22, 33, 44, 55] print("Result:", multiply(*arguments)) # unpack before passing
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:
def snakes(**kwargs): keyword_snake = "_".join(kwargs.keys()) value_snake = "_".join(kwargs.values()) return (keyword_snake, value_snake) key_value = { "first": "Biker", "second": "Rider", "third": "Driver" } print("Result:", snakes(key_value))
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:
def snakes(**kwargs): keyword_snake = "_".join(kwargs.keys()) value_snake = "_".join(kwargs.values()) return (keyword_snake, value_snake) key_value = { "first": "Biker", "second": "Rider", "third": "Driver" } print("Result:", snakes(**key_value))
Let's take a look at different representations to gain a better understanding:
Great! Now you can use unpacking in your program!
Thanks for your feedback!