If you are new to python or have been programming in python and you haven't started using Packing and Unpacking this article is for you.
Python provides additional convenience involving the treatments of tuples and other sequence types.
What the heck is Packing
In Python, a series of comma-separated objects without parenthesis are automatically packed into a single tuple. For example, the assignment
fruits = apple,orange,lemon
results in the variable fruits being assigned to the tuple (apple, orange, lemon). This behavior is called the automatic packing of a tuple.
Also, another common use of packing is when returning multiple values from a function. like so
this packs the return values into a single tuple object (x,y,z).
So what the heck is Unpacking in Python?
In the same light, Python can automatically unpack a sequence,
allowing one to assign a series of individual identifiers to the elements
of the sequence. As an example, we can write
a, b, c, d = range(1, 5) a, b, c, d = [1,2,3,4]
which has the effects of a=1,b=2,c=3,d=4. For this syntax, the right-hand
side expression can be any iterable type, as long as the number of variables on the left-hand side is the same as the number of elements in the iteration.
if they aren't equal an error will be raised:
a, b, c = [1,2,3,4] ValueError: not enough values to unpack (expected 3)
Unpacking can also be used to assign multiple values to a series of identifiers at once
a, b, c = 1, 2, 3
The right-hand-side is first evaluated i.e packed into a tuple before unpacking into the series of identifiers. This is also called a simultaneous assignment.
Another common usage of simultaneous assignment which can greatly improve code readability is when swapping the values of two variables like so:
a, b = b, a
With this command, a will be assigned to the old value of b, and b will be assigned to the old value of a. Without a simultaneous assignment, a swap typically requires more delicate use of a temporary variable, such as
temp = a a = b b = temp
You can also get the rest of a list like so:
a, b, c, *d = [1, 2, 3, 4, 5, 6] a => 1 b => 2 c => 3 d => [4, 5, 6]
In conclusion, using packing and unpacking during development can greatly improve the readability of your code and also solve some common issues with sequence assignment.
If you have any questions, kindly leave your comments below.
Kindly follow me and turn on your notification. Thank you!
Happy coding! ✌
It's social media for devs
Level up every day