Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Arbitrary Arguments (*args) | Function Arguments in Details
Mastering Python: Annotations, Errors and Environment

Arbitrary Arguments (*args)

In Python, the *args syntax is used to pass a varying number of arguments to a function. The *args parameter allows you to pass any number of positional arguments to a function, and it collects them into a tuple.

Let's implement the multiply() function that can accept a variable number of arguments:

The function multiply() accepts a variable number of arguments using the syntax *args. The arguments are then stored in a tuple called args. We can use a loop to multiply all the arguments together, as shown below:

Now, you can see that our function works with no arguments as well as with many arguments.

Note

The parameter *args is commonly referred to as variable-length argument or arbitrary argument list.

If we need a function that should take from one/two/... to many arguments, a combination of positional arguments and arbitrary arguments, such as *args.

In the example above, you can see that our function returned 150 when called with 2 or more arguments and raised a TypeError when called with fewer than 2 arguments.

It is important to note that the positional arguments should be defined before the optional arguments:

Everything was clear?

Section 2. Chapter 3
course content

Course Content

Mastering Python: Annotations, Errors and Environment

Arbitrary Arguments (*args)

In Python, the *args syntax is used to pass a varying number of arguments to a function. The *args parameter allows you to pass any number of positional arguments to a function, and it collects them into a tuple.

Let's implement the multiply() function that can accept a variable number of arguments:

The function multiply() accepts a variable number of arguments using the syntax *args. The arguments are then stored in a tuple called args. We can use a loop to multiply all the arguments together, as shown below:

Now, you can see that our function works with no arguments as well as with many arguments.

Note

The parameter *args is commonly referred to as variable-length argument or arbitrary argument list.

If we need a function that should take from one/two/... to many arguments, a combination of positional arguments and arbitrary arguments, such as *args.

In the example above, you can see that our function returned 150 when called with 2 or more arguments and raised a TypeError when called with fewer than 2 arguments.

It is important to note that the positional arguments should be defined before the optional arguments:

Everything was clear?

Section 2. Chapter 3
some-alt