How to return multiple values from a function in Python

Posted: 2019-09-18 / Tags: Python

Returning multiple values from a function is quite cumbersome in C and other languages, but it is very easy to do in Python.

See the following article for the basics of functions in Python.

Sponsored Link

Return multiple values using commas

In Python, you can return multiple values by simply return them separated by commas.

As an example, define a function that returns a string and a number as follows:

Just write each value after the return, separated by commas.

def test():
    return 'abc', 100

In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity.
Built-in Types - Tuples — Python 3.7.4 documentation

The return value is tuple.

result = test()

# ('abc', 100)
# <class 'tuple'>

Each element has a type defined in the function.

# abc
# <class 'str'>

# 100
# <class 'int'>

Of course, specifying an index that exceeds the number of defined return values will occur an error.

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

You can unpack and assign multiple return values to different variables.

a, b = test()

# abc

# 100

Same for 3 or more return values.

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

a, b, c = test2()

# abc

# 100

# [0, 1, 2]

Return list

Using [] returns list instead of tuple.

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

result = test_list()

# ['abc', 100]
# <class 'list'>
Sponsored Link

Related Categories

Related Articles