top of page

Splitting Sequences Through 'Unpacking' in Python

Introduction


Think of a present with multiple toys wrapped inside. In order to get to the toys, we must, of course, unpack them.

Python allows us to split or unpack sequences and store them in multiple variables all on a single line.


Here's all you need to know about unpacking different data types--whether that be a string, list, or even a dictionary!


Strings


Suppose I were to gather your first and last names:

first = input("Enter your first name: ")
last = input("Enter your last name: ")

printf(f"Hello, {first} {last}")

Perhaps a way to optimize this code (condense into one line) could be through assigning two variables at once:

first, last = input("Enter your full name: ").split(" ")
print(f"Hello, {first} {last}")

Note how first is everything behind the space, and last is everything after thanks to the split method.


Lists (and Tuples)


Perhaps even more practical, we can separate or unpack the values within a list using a special star operator (*):

list = [1, 5, 10]
num1, num2, num3 = *list

This may seem a bit useless, seeing as we can already index into lists using bracket notation, but unpacking can really come in handy when passing arguments to functions:

def addThree(num1, num2, num3):
	return num1 + num2 + num3

nums = [1, 5, 10]
print(addThree(*nums))

Much cleaner than having to do something like this, instead...

def addThree(num1, num2, num3):
	return num1 + num2 + num3

nums = [1, 5, 10]
print(addThree(nums[0], nums[1], nums[2]))

However, note that trying to unpack more (or less) values than the number of parameters or variables results in a TypeError.


Dictionaries


Finally, dictionaries--same idea, but slightly different syntax.

def addThree(num1, num2, num3):
	return num1 + num2 + num3

numsDict = {"num1": 1, "num2": 5, "num3": 10}
print(addThree(**numsDict))

Here is where it gets weird and slightly confusing (at least for me): The parameters of addThree must have the same name as the keys in numsDict for it to successfully extract the values from the dictionary.


That's just how Python does it. I don't make the rules.


In short, ** unpacks the key-value pairs of the dictionary, which get passed to our addThree function so long as the key names are the same as the parameter names.


Final Thoughts


Thanks for reading!

Comments


bottom of page