Using the Python args Variable in Function Definitions
00:19 This implementation works, but whenever you call this function you’ll also need to create a list of arguments to pass to it. This can be inconvenient, especially if you don’t know up front all the values that should go into the list.
This time, you’re no longer passing a list to the
my_sum() function. Instead, you’re passing three different positional arguments. The
my_sum() function takes all the parameters that are provided in the input and packs them all into a single iterable object named
args. Note here that
args is just a name. You’re not required to use the name
You can choose any name that you prefer, such as
integers. So, as you can see with this second version of the file, the function still works, even if you pass the iterable object as
integers instead of
All that matters here is that you use the unpacking operator, the single asterisk (
*). Bear in mind that the iterable object that you’ll get using the
* unpacking operator is not a
list, but rather a
tuple is similar to a
list in that they both support slicing and iteration. However, tuples are very different in at least one aspect: lists are mutable, where tuples are not. To test this, run the following code.
This script tries to change a value of a list. Here, you can see that this is a list being defined with the square brackets, and you are trying to reassign the value of the first list item using indexing, with the
02:03 Now let’s try to do the same with a tuple. Here, you can see the same values, except that they’re held together as a tuple. You can see what is being defined is a tuple with the use of the parentheses.
Become a Member to join the conversation.