top of page

Packing Variables in Python

Introduction


Previously, we looked at Python's unpacking feature--extracting values from sequences (lists, dictionaries, and the like) and storing them into individual variables.


Packing is the same idea, but the other way around.

This post will cover everything, from how multiple values can be packed into a sequence to practical applications of packing.


Arbitrary Function Arguments


Confusingly enough, we use the same star operator (*) when packing tuples / lists as we do with unpacking them.


However, this time, we're packing variables into a single argument, rather than unpacking a sequence into multiple argument variables:

def add(*nums):
	return sum(nums)

add(1, 10, 15, 20)

Notice how the * is applied to nums. This can prove especially useful when we don't know how many arguments a function will take.


So why does this work?


Well, when we attempt to store multiple values into a variable, Python automatically packs them into a tuple:

myTup = 1, 2, 3
print(myTup)  # Output: (1, 2, 3)

So, in our previous program, Python is packing the four arguments we passed to add into a tuple called nums, which is then unpacked into four values using the * operator.


Packing and Unpacking Simultaneously


Another of Python's feature is to allow for split a tuple between variables like the example below.

nums = (1, 2, 3, 4, 5)
a, *rest = nums
print(a)     # Output: 1
print(rest)  # Output: [2, 3, 4, 5]

Here, not only are we packing values 2, 3, 4, and 5 into a list (which is the default), but we're also unpacking at the same time!


Packing Dictionaries


We can also use packing to merge multiple dictionaries together.

info1 = {"name": "Ulf", "number": "+1 (212) 658-3916"}
info2 = {"email": "ulf@gmail.com", "address": "123 Boulevard"}

contact = {**info1, **info2}
print(contact)	# prints both dictionaries merged together into one

Again, here we're both packing and unpacking.


The double-star operator (**) is used to unpack the dictionaries, and then the curly brackets help pack those unpacked values into a single variable, contact!


So, really, we're never using ** to pack--just to unpack.


Final Thoughts


Long story short: both packing and unpacking can prove useful (especially together) in breaking down sequences, merging them, and in situations where you don't know the number of arguments your function will take.


Thanks for reading!


Comments


bottom of page