Variable Number of Arguments in Python
Learn how variable number of function arguments are handled in Python.
Python, as well as other languages, has built-in functions and constructions that can take a variable number of arguments. Consider, for example, string
interpolation functions (whether it be by using the %
operator or the format
method for strings), which follow a similar structure to the printf
function in C, a first positional parameter with the string
format, followed by any number of arguments that will be placed on the markers of that formatting string.
Besides taking advantage of these functions that are available in Python, we can also create our own, which will work in a similar fashion. Here, we will cover the basic principles of functions with a variable number of arguments, along with some recommendations, so that afterward we can explore how to use these features to our advantage when dealing with common problems, issues, and constraints that functions might have if they have too many arguments.
Syntax for variable number of positional
arguments
For a variable number of positional
arguments, the star symbol (*
) is used, preceding the name of the variable that is packing those arguments. This works through the packing mechanism of Python.
The packing mechanism in Python
Let's say there is a function that takes three positional arguments. In one part of the code, we conveniently happen to have the arguments we want to pass to the function inside a list
, in the same order as they are expected by the function.
Instead of passing them one by one by the position (that is, list[0]
to the first element, list[1]
to the second, and so on), which would be really un-Pythonic, we can use the packing mechanism and pass them all together in a single instruction:
Get hands-on with 1400+ tech skills courses.