As one of the most unique syntaxes in Python, *args will give us lots of flexibility and convenience during programming. I would say that they reflected what is “Pythonic” and the Zen of Python.
However, I found that they are challenging to be understood by learners. In this article, I’ll try my best to explain this iconic concept in Python and provide practical use cases based on my knowledge. I hope it will help you to understand it better.
*args stands for “arguments”. It allows us to pass any number of positional arguments (will explain later) to a function. Inside the function, we can get all of the positional arguments in a tuple. So, we can do whatever with the tuple of arguments in the function.
Here is a simple example of *args.
def add_up(*numbers):
result = 0
for num in numbers:
result += num
return resultprint(add_up(1, 2, 3))
When we call this add_up() function, we have passed three positional arguments to it. In Python, if we don’t specify the names of the arguments, they will be treated as positional arguments. These arguments are determined based on their position, so they are called positional arguments.
In the above example, all the positional arguments 1, 2, 3 were passed into the function and “caught” by the *numbers parameter. Then, we can access all these arguments from this parameter numbers. The asterisk * simply tells Python that this is a *args type parameter. After that, a simple for-loop adds up all the arguments and prints the result.
The beauty of *arg, as above-mentioned, is that it can take any number of positional arguments. Therefore, we can pass more arguments if we need to.
print(add_up(1, 2, 3, 4))
Here, we can verify if the variable numbers is a tuple by adding one line to the original function.
def add_up(*numbers)…