*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.

1def add(*numbers):
2    result = 0
3    for number in numbers:
4        result += number
5    return result
6print(add(1, 2, 3, 4))  # Outputs: 10

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:

1def greet(greeting, *names):
2    for name in names:
3        print(f"{greeting}, {name}!")
4greet("Hello", "Alice", "Bob", "Charlie")  # Outputs: "Hello, Alice!", "Hello, Bob!" etc.

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.