Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

Using the Python args Variable in Function Definitions

This lesson is from the Real Python video course by Rich Bibby.

00:00 There are a few ways that you can pass a varying number of arguments to a function. The first way is often the most intuitive for people that have experience with collections.

00:09 You simply pass a list or a set of all the arguments to your function. So for the function my_sum(), you could pass a list of all the integers that you need to add.

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.

00:33 This is where *args can be really useful, because it allows you to pass a varying number of positional arguments. Take a look at another example.

00:41 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 args.

01:01 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 args.

01:14 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.

01:27 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.

01:40 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 0.

01:51 This means the value located at the very first index of the list should be updated to 9. If you execute this script, you’ll see that the list indeed gets modified.

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.

02:15 So this time, when you try to change the value at index 0 by running the script, you’ll see that the Python interpreter returns an error.

02:24 This is because a tuple is an immutable object, and its values cannot be changed after assignment. Keep this in mind while you’re working with tuples and *args.

You must own this product to join the conversation.