Multiple Return Values in Python

Python has built-in support for multiple return values. This feature is often used in idiomatic Python, for example, to return both result and error values from a function.

def vals():
    # The function returns 2 integers
    return 3, 7

def main():
    # Here we use the 2 different return values from the
    # call with multiple assignment
    a, b = vals()
    print(a)
    print(b)

    # If you only want a subset of the returned values,
    # use the underscore '_' as a placeholder
    _, c = vals()
    print(c)

if __name__ == "__main__":
    main()

To run the program, save it as multiple_return_values.py and use python:

$ python multiple_return_values.py
3
7
7

In Python, functions can naturally return multiple values as tuples. The (int, int) notation isn’t necessary as Python is dynamically typed.

The main() function isn’t required in Python, but it’s a common convention to use it as the entry point of the script.

The ability to ignore certain return values using _ is a common Python idiom, similar to the blank identifier in other languages.

Accepting a variable number of arguments is another nice feature of Python functions; we’ll look at this next.