Assigning Multiple Variables with Unpacking
In this lesson, you'll learn how to assign multiple variables at once using unpacking. We'll demonstrate how you can extract values from various iterables like strings and lists and assign these values to multiple variables.
So far, if we wanted to create multiple variables, we had to do this in multiple lines of code, like this:
x = 10
y = 20
z = 30
But there's a more efficient way to do this!
It's called unpacking. Unpacking is the process of extracting values from an iterable (like a list or tuple) and assigning them to multiple variables in a single statement.
Let's see how this works:
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z)
We start with a tuple called coordinates, which contains 3 values. Then, we unpack each value from coordinates and assign them to the variables x, y, and z.
We can shorten this even further into a single line of code:
x, y, z = (10, 20, 30)
print(x, y, z)
Now, we are creating and assigning the variables all in one line.
If you want to, you can even skip the parentheses of the tuple when assigning multiple variables, like this:
x, y, z = 10, 20, 30
print(x, y, z)
In this case, Python implicitly treats the values 10
, 20
, and 30
as a tuple, allowing us to assign them directly to the variables.
As you can see, with this unpacking technique, we have transformed our original multiline assignment into a more efficient one-liner:
# individual assignments
x = 10
y = 20
z = 30
# assignments with unpacking
x, y, z = 10, 20, 30
What will be the output?
data = (1, 2)
a, b = data
print(b)
What will be the output?
data = (1, 2)
b = data
print(b)
What will be the output?
a, b = 1, 2
print(a)
One thing to keep in mind when using this unpacking technique is that the number of variables must match the number of values being unpacked.
For example, here we attempt to unpack a tuple with 3 values and assign them to only 2 variables:
x, y = 10, 20, 30
As you can see, we run into an error.
An error is also triggered if your tuple contains fewer values than the number of variables you want to assign:
x, y, z = 10, 20
So far, we've only been unpacking tuples, whether explicitly with parentheses or implicitly without them.
But unpacking isn't limited to tuples—you can unpack all iterables in Python.
An iterable is any Python object that can be iterated over, for example in a loop.
Here are some examples of unpacking other types of iterables:
# unpacking a list
x, y, z = [10, 20, 30]
print(x, y, z) # 10, 20, 30
# unpacking a string
a, b, c, d, e = 'hello'
print(a, b, c, d, e) # h, e, l, l, o
# unpacking dictionary keys
k1, k2 = {'a': 1, 'b': 2}
print(k1, k2) # a, b
# unpacking dictionary values
v1, v2 = {'a': 1, 'b': 2}.values()
print(v1, v2) # 1, 2
What will be the output?
a, b = 'start', 'end'
a, b = b, a
print(a)
What will be the output?
a, b = 'hi'
print(b, a)
What will be the output?
a, b, c = 'code'
print(c, b, a)