Multiple Unpackings in a Function Call
00:00 Now let’s take a look at how we can unpack multiple items in a single function call. Starting with version 3.5, Python introduced support for unpacking multiple items, and we’re going to see that with this very simple function.
This function is going to take an arbitrary number of positional arguments and pack them in a tuple. I’ve put this in a file called
multi_unpacking. The function
g() we will see momentarily as it applies to dictionaries.
multi_unpacking, let’s go and import both of them. So,
f() is expecting an arbitrary number of positional arguments, but I have three collections with values I want to use in a single function called
f(). I have a list containing the numbers
3, I have a tuple containing the numbers
6, and I have a set containing the numbers
So if I want
f() to apply to all of these, I’ll need to unpack them. I can do that by specifying each one, unpacked, separated by commas. And so these will all be unpacked, which will eventually send nine different argument values to
f(), which will then pack them all into a tuple.
And this particular function is simply going to display each value one at a time. And so there we see all of our arguments. And remember, there is no order to a set, and so the order in which Python internally represents the set and the numbers in the set might not match the order that they were put in, so don’t be bothered that the set displayed as
The same thing can be done with dictionaries. If I have a function, which I’ve called
g() here, which is going to pack any number of keyword arguments into a single dictionary, I can, should I have a couple of dictionaries defined—let’s say that
d1 is equal to the dictionary that maps
2, and I have a second dictionary that maps
4, and I want to apply that to
g() is expecting any number of keyword arguments.
I can unpack the first dictionary, and then separated with a comma, I can then tell it to unpack the second dictionary. And what
g() will see are going to be four key-value pairs. Now, let’s remember what
g() is going to do.
g() is going to collect all of the keyword arguments into a dictionary, and then for each item, we’re going to find the key and the value, and then just display the mapping, the keyword to the argument value.
And you don’t have to have variables created. You can do unpackings with literals. So you can say, for example, call
f() is expecting any number of positional arguments. So I can have a list and then another list.
So again, the two dictionaries will be unpacked, passed as key-value pairs to represent keyword arguments and their appropriate values. And then
g() sees them, packs them all into a single dictionary, where we can see the key-value pairs that it was given.
Become a Member to join the conversation.