00:00 In this lesson, you’ll learn about unpacking tuples. Unpacking is an interesting concept in Python that allows you to do some fun things. Let’s backtrack a tiny bit and go back to how you can create a tuple literal, and you can do it by listing values separated by commas.
You can assign elements of a tuple to multiple variables by unpacking the tuple, and that’s what’s called tuple unpacking. So with the
rgb_lime_green that I’ve defined in the previous slide, you can assign each individual element of the tuple to variables with the syntax of saying
red, green, blue = and then the tuple literal on the other side.
I could define this without the parentheses as well, but I generally tend to always write the parentheses when I define a tuple. Okay, and now I can unpack this tuple,
red, green, blue = rgb_lime_green, and now I can see that
red points to
50 again. Now you don’t have to go the path across this intermediate variable here that I defined.
and now I’ve overwritten the variables above. And now the separate values all point to
0 in this case. Whether you use parentheses here or not, or whether you use an intermediate variable or not, what you do is on the right side of the assignment statement, you have a tuple literal, and on the left side you have the equal amount of variables that you have elements in the tuple, and then Python’s tuple unpacking assigns the first element to the first variable, the second element to the second variable, and the third element to the third variable, et cetera if there are more elements.
03:41 It’s a fun trick, but you shouldn’t overdo it because this only makes sense if it makes your code more readable. An example here of a not well readable way of doing this, which is just too many different variables, too many unrelated values, and that’s confusing and it would make more sense to structure this differently.
03:58 What could be readable is if both of the values are quite related to each other—for example, in a geographical location, and you have latitude and longitude, then you could assign them in this way in just one line instead of assigning them on two separate lines.
Let’s try that out. If you would try to do something like
b, c and not provide enough values—so here I’m providing three variables,
a, b, c, but only two values,
2—then Python is going to throw a
ValueError that there aren’t enough values to unpack.
And here you can see the word that Python is trying to unpack the tuple literal
1, 2 that you have here on the right side of the assignment statement, and it expected three, but got only two, and the same goes the other way.
So if you only have two variables, but you give it three values, then Python’s also going to complain with a
ValueError, and it tells you that there’s too many values to unpack, and it only expected two, because there’s only two variables where to put the values into.
Become a Member to join the conversation.