Argument Tuple Packing
00:18 To illustrate how this might be useful, consider writing a function that’s going to take the average of a bunch of numbers. How many parameters should it have? Three? Well, that’s useful if you’re taking the average of three numbers, but if you try to use more or less, you’re going to get an error. Specify some default values?
Python provides a mechanism to solve this, and we’re going to take a look at that now. It’s called argument tuple packing. The syntax is when you precede a parameter name in a function definition with an asterisk (
It’s an indication that you’re going to use this feature of argument tuple packing. What happens is the function can then provide as many arguments as it needs and they will all be packed into a single tuple using that particular parameter name. Now, conventionally, we use the word
args for that parameter.
01:43 That’s not a requirement, but it’s what every other Python programmer does and so you’ll see that in the programs that you read and it would be best practice to use that in the programs you write.
So, to see how that works, take a look at this function. This function
f() takes one parameter,
args, using argument tuple packing. And just to see how it all fits together, we’re going to print the value of
args, that tuple.
Here, I’ve put this function into a file and we’ll come back to the
avg() (average) function starting at line 10 in a moment. But again, here’s our parameter variable using argument tuple packing.
So, we’re going to call function
f() and we’re just going to provide it three arguments,
3. These are going to get packed as a tuple, and so that’ll be the first line of output that we see.
Then we are told that its type is of
<class 'tuple'> and that its length was
3. And then we can see individually the three arguments that we provided.
3. Let me try this again, and this time, let me use some strings, and I’ll use a different number of strings, so
So, we’ve provided five separate argument values. They’re packed into a single tuple. The type of that parameter is a
tuple and its length was
5, and here are the individual argument values that we gave it in the function call.
So we have a simple accumulating loop, start an accumulator variable
total set to
0, and as we iterate through our tuple of arguments, we increase the
total by that amount. Once we’re done,
total has the sum of all of the values that were given as parameters and we divide by that length. There were a couple of sample runs,
Any number of numeric arguments that can be provided, and this function will find the average of all of them, packing them all into a single tuple, then in a
for loop accumulating the sum of each of the values in that tuple, and then dividing by the length of the tuple, which contains the number of argument values given.
Become a Member to join the conversation.