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
FEATURED TAGS
algorithm
algorithmproblem
architecturalpattern
architecture
aws
c#
cachesystem
codis
compile
concurrentcontrol
database
dataformat
datastructure
debug
design
designpattern
distributedsystem
django
docker
domain
engineering
freebsd
git
golang
grafana
hackintosh
hadoop
hardware
hexo
http
hugo
ios
iot
java
javaee
javascript
kafka
kubernetes
linux
linuxcommand
linuxio
lock
macos
markdown
microservices
mysql
nas
network
networkprogramming
nginx
node.js
npm
oop
openwrt
operatingsystem
padavan
performance
programming
prometheus
protobuf
python
redis
router
security
shell
software testing
spring
sql
systemdesign
truenas
ubuntu
vmware
vpn
windows
wmware
wordpress
xml
zookeeper