Arbitrary Argument Lists in Python

An arbitrary argument list is a Python feature to call a function with an arbitrary number of arguments. It’s based on the asterisk “unpacking” operator *. To catch an arbitrary number of function arguments in a tuple args, use the asterisk syntax *args within your function definition. For example, the function def f(*args): ... allows for an arbitrary number, and type, of arguments such as f(1), f(1, 2), or even f('Alice', 1, 2, (3, 4)).

This quickstart tutorial introduces a useful Python trick: arbitrary argument lists.

Syntax & Calls

Syntax: f(*args): ...
Calls: 
 f(1)                                                     --->      args = (1,)
 f(1, 2)                                              --->      args = (1, 2)
 f('Alice', 1, 2, (3, 4))         --->      args = ('Alice', 1, 2, (3, 4))

Example Arbitrary Arguments

Example: Suppose, you want to create a function that allows an arbitrary number of arguments. An example is recognizing faces in images where each image consists of one or more pixel arrays.

Solution Idea: You can achieve this by adding the asterisk-prefixed *pixelArrays as a function argument. This packs an arbitrary number of arguments into the variable pixelArrays and stores it as a tuple. You can access the tuple values via indexing or iteration in a for loop.

def recognize_faces(*pixelArrays):
    for arr in pixelArrays:
        for i in range(1, len(arr)):
            if arr[i] == arr[i-1]:
                print('Face Detected')



recognize_faces([1, 0, 1, 1], [0, 0, 0, 0], [1, 0, 0, 1])
'''
Face Detected
Face Detected
Face Detected
Face Detected
Face Detected
'''

This dummy code goes over each pixel array and checks if two subsequent values are the same. If this is the case, it detects a face. While this obviously doesn’t make sense, it still shows how to iterate over each argument when an arbitrary number of arguments may be available.

Let’s test your skills with the following code puzzle.

Python Puzzle Arbitrary Argument Lists

def f(a, *arguments):
    print(a)
    for arg in arguments:
        print(arg)

f("A", "B", "C")

What is the output of this code snippet?

Note: You can combine both types of arguments: formal arguments (e.g. a in the puzzle) and an arbitrary argument list (e.g. *arguments in the puzzle). If called with many arguments, the arbitrary argument list will handle all but the formal arguments.


Are you a master coder?
Test your skills now!

Related Video

Leave a Comment

Your email address will not be published. Required fields are marked *