How to return multiple return values in a Python function

Money and Business

In C, returning multiple return values from a function is quite tedious, but in Python, it is very easy to do.

Return separated by commas

In Python, you can simply return a comma-separated list of strings or numbers.

As an example, define a function that only returns a string and a number as shown below, with each separated by a comma after the return.

def test():
    return 'abc', 100

In Python, comma-separated values are considered tuples without parentheses, except where syntactically necessary. Therefore, the function in the example above will return a tuple with each value as an element.

It is the comma that creates the tuple, not the round brackets. Round brackets can be omitted, except in the case of empty tuples or when necessary to avoid syntactic ambiguity.
Built-in Types — Python 3.10.0 Documentation

The type of the return value is a tuple.

result = test()

print(result)
print(type(result))
# ('abc', 100)
# <class 'tuple'>

Each element will be of the type defined by the function.

print(result[0])
print(type(result[0]))
# abc
# <class 'str'>

print(result[1])
print(type(result[1]))
# 100
# <class 'int'>

Error if you specify an index that exceeds the number of return values you defined.

# print(result[2])
# IndexError: tuple index out of range

It can be unpacked and multiple return values can be assigned to separate variables.

a, b = test()

print(a)
# abc

print(b)
# 100

The same applies if you want to specify three or more return values instead of just two.

def test2():
    return 'abc', 100, [0, 1, 2]

a, b, c = test2()

print(a)
# abc

print(b)
# 100

print(c)
# [0, 1, 2]

Returns a list.

[]If you enclose it with this, the return value will be a list instead of a tuple.

def test_list():
    return ['abc', 100]

result = test_list()

print(result)
print(type(result))
# ['abc', 100]
# <class 'list'>
Copied title and URL