Functions are very useful in the Python computer programming language as they help the coder to group utilities together with the main purpose of accomplishing a specific goal. Not only this, but the function can also help the Python coder to stop repeating themselves in their Python based projects.
A real world function, part of a Python project, takes a number of arguments as input and uses inner logic to process them based on the algorithms defined by the computer programmer. Through this article, you are going to learn how to make use of the *args Python syntax to automatically pass arguments to your custom Python function.
Before going any further with this short tutorial, make sure to launch a new Python interactive shell so you can practice the code by yourself. Once you have managed to launch a new Python interactive shell on your own operating system, define the following function.
What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.
def find_sum(a, b):return a + b
The above Python function takes two arguments as input, and then finds their sum and returns it back to the caller. As most of you may know, the arguments of the above function should be numbers.
For example, the following piece of Python code finds the sum of the numbers 5 and 3.
find_sum(5, 3)
Once the piece of Python code shown above gets executed in my Python interactive shell, the following output gets displayed on my console.
8
Suppose that the Python based application which you are writing, requires that you find the sum of two numbers which are stored in a list.
Since the function which we have defined in our Python interactive console takes two arguments as input, we can pass a list object to it, by making use of the syntax shown below.
find_sum(*args)
Based on my experience with the Python computer programming language, the above syntax unpacks the list object automatically.
Now, let’s declare the following list object in our Python interactive console.
l = [1, 2]
To find the sum of the elements found in the above Python list object, we make use of the code being shown below.
find_sum(*l)
Once the above piece of Python code is being run in my Python interactive shell, I get the following output printed on my console.
3
Final thoughts
Through this tutorial you learned through a practical example how to pass arguments inside a Python function, by making use of the *args syntax, a syntax which unpacks a list object automatically.