A comprehensive guide of *args with practical examples
As one of the unique syntaxes in Python, *args will give us a lot of flexibility and convenience during programming. I might say that they reflected what’s “Pythonic” and the Zen of Python.
Nonetheless, I discovered that they’re difficult to be understood by learners. In this text, I’ll try my best to clarify this iconic concept in Python and supply practical use cases based on my knowledge. I hope it can make it easier to to grasp it higher.
*args stands for “arguments”. It allows us to pass any variety of positional arguments (will explain later) to a function. Contained in the function, we will get the entire positional arguments in a tuple. So, we will do whatever with the tuple of arguments within the function.
Here is an easy example of *args.
def add_up(*numbers):
result = 0
for num in numbers:
result += num
return resultprint(add_up(1, 2, 3))
After we call this add_up() function, we have now passed three positional arguments to it. In Python, if we don’t specify the names of the arguments, they might be treated as positional arguments. These arguments are determined based on their position, in order that they are called positional arguments.
Within the above example, all of the positional arguments 1, 2, 3 were passed into the function and “caught” by the *numbers parameter. Then, we will access all these arguments from this parameter numbers. The asterisk * simply tells Python that it is a *args type parameter. After that, a straightforward for-loop adds up all of the arguments and prints the result.
The fantastic thing about *arg, as above-mentioned, is that it may well take any variety of positional arguments. Subsequently, we will pass more arguments if we’d like to.
print(add_up(1, 2, 3, 4))
Here, we will confirm if the variable numbers is a tuple by adding one line to the unique function.
def add_up(*numbers)…