【Python】Basics - 函数返回值

Posted by 西维蜀黍 on 2019-10-27, Last Modified on 2024-01-09

Introduction

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

Return Multiple Values

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.

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'>

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'>

Reference