Argument Tuple Unpacking
00:00 You saw in the last lesson how you can write a function to take any number of arguments and have them packed into a single parameter as a tuple. But when using functions, you can go the other way as well.
00:12 If you have a function that takes a set number of positional parameters and you have that many values in a tuple, you can unpack that tuple to use those values as the arguments to that function.
For example, here’s a function
f() that takes three parameters, and all we’re going to do here is display the value of each parameter when it’s called. So, nothing terribly interesting or exciting here, nothing that uses asterisks or packing of any kind.
I’m just going to call this
t, set it equal to
(1, 2, 3). I’ve been doing work with these values and they’ve been stored in a tuple because it makes other things that I’m doing convenient, but now I need to apply
f() to those values.
f() is expecting three arguments. I only have the one tuple, but if I use the asterisk in a function call, it’s understood that we want to unpack that tuple into individual values to be passed as positional parameters to that function. And so we can see that, again, the first parameter
1, second parameter
2, the third parameter
3. I change
t to be something else, a tuple of strings,
and unpack that to give
f() the three parameters that it’s expecting. And you can use unpacking and packing together. So if we have a function, that’s going to pack any number arguments into a single parameter variable. And here, we’re just going to display information about the argument. We’re going to display its type and its value.
g() is expecting individual parameters to be packed into a tuple.
a already is a collection of some type, but in order to use
g() properly, we have to unpack that so that
g() can repack it into its own tuple.
g() gets a tuple as opposed to just writing a function that uses the list. Several reasons you might want that: Tuples can’t be changed, and so the function is going to work in a way that never even attempts to change the parameter.
If your collections are rather large, working on a tuple might be a bit more efficient behind the scenes than working on a list. So, there are actually some reasons why you would actually choose to do that instead of just writing a function
g() that takes a list.
04:31 In the next lesson, we’re going to take a look at something similar: not packing arguments as tuples, but packing them as dictionaries if we’re using keyword parameters, and we’ll take a look at what the differences are with that.
Become a Member to join the conversation.