There are many ways to Python function return multiple values like using a comma but that is returned in the form of a tuple.
Other ways are using a tuple, list, and dictionary.
Example function return multiple values in Python
Simple example code.
Using comma
Python function returns multiple values by simply returning them separated by commas. This method return value in tuple.
def test():
return 'abc', 100
print(test())
Output:
Using a tuple
This method is not recommended because without using tuple still, you will get a return in tuple formate.
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y1
return (y0, y1, y2)
print(f(1))
Output: (2, 3, 8)
Using a dictionary
With this method, you can keep track of the returned values using the keys.
def name():
n1 = "ABC"
n2 = "XYZ"
return {1: n1, 2: n2}
print(name())
Output: {1: ‘ABC’, 2: ‘XYZ’}
Using a list
Using bracket [ ] returns list instead of tuple.
def test():
return ['abc', 100]
print(test())
Output: [‘abc’, 100]
Using a class
class ReturnValue:
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y1
return ReturnValue(y0, y1, y2)
Using a dataclass (Python 3.7+)
from dataclasses import dataclass
@dataclass
class ReturnValue:
y0: int
y1: float
y3: int
def total_cost(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y1
return ReturnValue(y0, y1, y2)
print(total_cost(1))
Output: ReturnValue(y0=2, y1=3, y3=8)
Using Object
class Test:
def __init__(self):
self.str = "ABC"
self.x = 10
def fun():
return Test()
t = fun()
print(t.str)
print(t.x)
Output:
ABC
10
Do comment if you have any doubts and suggestions on this Python function code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.