*args
What is *args?
*args
in Python signifies variable number of non-keyworded arguments. This means that you can pass any number of arguments to a function only constrained by the amount of system resources.
The syntax is to use the asterisk (*) before the parameter name in the function definition. This collected arguments are organized into a tuple.
How to use *args?
Let’s illustrate the use of *args
with an example. Let’s define a function to perform addition of numbers.
On calling the function add
with four arguments, all will be bundled into a tuple and passed to the function. The for loop running inside the function, then adds up the numbers.
Advantages of *args
*args
provides many benefits. It increases the flexibility of your code. You can create more generic functions that aren’t limited by a fixed number of arguments. This is useful when you want to pass a list or tuple of arguments to a function.
Note
The name args
is just a convention and you are free to use a different name. However, using args
helps other developers understand your code better.
*args with normal parameters
*args
can be used with normal parameters in function definition. However, *args
must be placed after all the required parameters to avoid ambiguity. Look at this example:
In this example, the parameter greeting
is a regular argument whereas names
is an *args
argument.
In conclusion, *args
is one of the tools that makes functions in Python powerful and flexible. It allows you to make your code cleaner and less cluttered by grouping multiple arguments together. Using *args
correctly can make your functions more flexible and easier to maintain.