Packing is a handy Python tool that provides a dynamic way to pack and unpack values into a single data structure or take them out and assign them to multiple variables. This process greatly improves the reliability and adaptability of your code.
In Python, “packing” refers to the process of putting values into a new tuple or list by separating them with commas. This can be done with an assignment statement where the left-hand side is a tuple or list of variables and the right-hand side is another tuple or list of values.
For example, you might have three variables, which are number1, number2 and number3, which are defined as such:
1 2 3 | number1 = 1 number2 = 2 number3 = 3 |
You can pack those variables into a tuple like so:
1 | myTup = (number1, number2, number3) |
Or a list like so:
1 | myList = [number1, number2, number3] |
You can also use the * operator (which is used as both power and multiplication operators). Before we see how that works with packing, let me show you how the * operator works. We’ll define a function called sumOf and use the * operator like so:
1 2 3 4 | def sumOf(*nums): print('Our numbers are:', nums) return sum(nums) print('Adding them up, we get:', sumOf(10, 20, 30)) |
Know that *nums stores the series of numbers and then the sum() function adds them together. So, when run, the output of the above would be:
1 2 | Our numbers are: (10, 20, 30) Adding them up, we get: 60 |
Back to packing, we can use the * operator with packing like so:
1 2 3 4 | num1=1 num2=2 num3=3 *num,=num1,num2,num3 |
But how do we use packing in actual Python code?
Packing with Tuples
Remember, a tuple is an immutable list, so it cannot be changed once created. Tuples are great options for storing data that you don’t want to be modified. Let’s say we want to create a simple program, using tuples and packing to sum up a string of numbers. We’ll define our custom function as such:
1 2 | addPack(*myTuple): return sum(myTuple) |
Above, we’re sending a dynamic number of arguments to the addPack function and are accessing them via a single myTuple parameter by using the * operator.
Next, we pack our arguments with the following two lines:
1 2 | print(addPack(2, 3, 4, 5, 6, 7, 8)) print(addPack(5, 10, 15, 20)) |
Because we’re using dynamic arguments for packing, we could have continued with our numbers like so:
1 2 | print(addPack(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)) print(addPack(5, 10, 15, 20, 25, 30, 35, 40)) |
When we run the application, it will add the numbers in both tuples and total them together. What this has done is pack the addPack function with variables from the print functions.
You can also collect multiple values with packing and use certain parts in different ways. Take, for instance, this piece of Python code:
1 2 3 4 5 | name="John Jacob Jinglheimer Schmidt" first_name, *rest_name=name.split() print("Complete Name:", name) print("First Name Only:", first_name) print("Remaining names:", rest_name) |
The above performs what is called a string split to collect only the first name of someone with multiple names. What this does is collect the first name in one variable and the remaining names into another (hence the string split).
The output of the above packing example would be:
1 2 3 | Complete Name: John Jacob Jinglheimer Schmidt First Name Only: John Remaining names: ['Jacob', 'Jinglheimer', 'Schmidt'] |
Unpacking with Tuples
In Python, unpacking is the process of extracting values from a sequence and assigning them to multiple variables. We achieve unpacking with the assignment operator on the left side and an iterable object on the left side.
For example, we can unpack with a tuple like so:
1 2 3 | myTuple = (1, 2, 3) a, b, c = myTuple print(myTuple) |
The output of the above would be:
1 | (1, 2, 3) |
Another example of unpacking a tuple looks like this:
1 2 3 4 5 6 | fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red) |
What we’ve done is assign values to multiple variables and then unpack them. The output of the above script would be:
1 2 3 | apple banana cherry |
We can unpack a list like this:
1 2 3 | myList = [10, 20, 30] a, b, c = myList print(myList) |
The output of the above would be:
1 | [10, 20, 30] |
We can also unpack dictionaries (an unordered collection of data in the format of a key-value pair) like so:
1 2 3 | myDict = {'fname': 'Jack', 'lname': 'Wallen', 'country': 'USA'} fname, name, country = myDict.values() print(myDict.values()) |
The output of the above script would be:
1 | dict_values(['Jack', 'Wallen', 'USA']) |
Unpacking allows you to assign values from a sequence to multiple variables, using only a single line of code.
By using packing and unpacking you can create assignments with a single statement and catch several values with a single identifier, thereby making your code much easier to read. These two features allow for much more flexible handling of function arguments and streamlined data manipulation.
TRENDING STORIES
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don't miss an episode. Subscribe to our YouTubechannel to stream all our podcasts, interviews, demos, and more.