note.nkmk.me

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 with Python.

See the following post for the definition of functions by def.

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()

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

Each element has a type defined in the function.

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

print(result[1])
print(type(result[1]))
# 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()

print(a)
# abc

print(b)
# 100

Same for 3 or more return values.

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

a, b, c = test2()

print(a)
# abc

print(b)
# 100

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

Return list

Using [] returns list instead of tuple.

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

result = test_list()

print(result)
print(type(result))
# ['abc', 100]
# <class 'list'>
Sponsored Link
Share

Related Categories

Related Posts