Python supports two kinds of parameters, positional and keyword. Positional arguments are specified by their position in the argument list. They are required and must be provided before any keyword arguments. Keyword arguments are not required because they are provided with default values but when they are used, they are provided by name.
The image below shows the contextual help for the sorted() function. An iterable (e.g. a tuple or list) is provided as a positional argument, expected as the first argument, and keyword arguments, key and reverse, can also be supplied.
The *args parameter allows multiple positional arguments to be passed to a function. The number can be variable because the number of arguments does not need to be specified in advance. Arguments are packed into a tuple and passed to the function.
Using a function that contains an *args parameter
The image below shows the contextual help for the min() function. It shows two ways that the function can be used. The first uses an iterable – values are provided in a tuple or list and the smallest is returned.
The second lists *args as a parameter and is the form we will use for this example. The *args parameter is listed after the positional parameters arg1 and arg2. This tells us that the function requires at least two positional arguments (values) but can also take an unlimited number of other positional arguments (values).
If we provide a single value only, an error will be returned.
The function will return a result if two or more values are provided.
Using *args in your custom functions
You can add a lot of flexibility to your own custom functions by including an *args parameter in your function definition, after any other positional parameters. If you choose to do this, it is not necessary to use the name args but the * is required. For example, the parameter could be called *objects instead.
In the example below, a simple summary function has been defined. It will return the minimum, maximum and sum of any values passed to it. The use of *args means that it will work with any number of values provided.
Learn more about Python, check out our Python Training Courses. Available in person in our CBD locations or remote online across Australia.
View Python Courses