Friday, May 20, 2022

Tuple unpacking

To create a tuple, we simply create a variable and assign items to it, separated by commas. The term for this is packing a tuple, because the data is packed into the tuple, all wrapped up and ready to go. To remove items from a tuple, you simply unpack it, as shown in the following screenshot:


In line 60, the tuple is packed with a sequence of numbers, and in line 61, the items in the tuple (the numbers) are unpacked and assigned to individual variables. Lines 62-65 demonstrate that each number has been assigned to separate variables.

Line 66 shows the same thing, except the tuple parentheses, have been dropped to show that they aren't necessary.

Tuple unpacking is nice when you have a lot of items to work with. Rather than having a separate variable for each item, you can pack them all into a tuple and work with that. When you need to, you can unpack the tuple and work with the individual items directly.

One benefit of tuple packing/unpacking is that you can swap items in place. With other languages, you have to create the logic to swap variables; with tuples, the logic is inherent in the data type, as shown in the following screenshot:


Tuple unpacking and in-place swapping is one of the neatest features of Python, in my opinion. Rather than creating the logic to pull each item from a collection and place it in its own variable, tuple unpacking allows you to do everything in one step. In-place swapping is also a shortcut; you don't need to create temporary variables to hold the values as you switch places.

Next topic of discussion will be Sets.

Share:

0 comments:

Post a Comment