Python function return multiple values ( ython return multiple values ) : The python function will return multiple variables and these variables can be stores in variables directly. The function is not required to return the variable and return value zero, one, two etc. The variables are defined in the function known as the in function because of scope. We will return the variables from function and return the simple variable. It will return multiple values which can be stored in variables.
def func(x):
y0=x+1
y1=x*3
y2=y0**3
return(y0, y1, y2)
The solution is used for the dictionary.
def func(x):
Y0=x+1
Y1=x*3
Y2=y0**3
Return{‘y0’:y0, y1,’y2’:y2}
Class ReturnValue (obj):
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**3
Return ReturnValue(y0, y1, y2)
def func(x)
result=[x+1]
result.append(x*3)
result. append (y0**3)
return result
Using the yield to return the multiple values in case of return a huge number of values using sequence and consume the system resource.
Example:-
def func(x):
y0=x+1
Yield y0
Yield x*3
Yield y0 **3
The best method used to return the values from function:-
The requirement and the need are important to select the method to return values from the function.
The dictionary route is also used to setup the work and also the class will help to avoid the confusion.
ClassTest:
def_init_ (self):
self.str=”Welcome python”
self.x=20
def fun ():
return Test ()
t=fun ()
print (t.str)
print (t.x)
Output:-
Welcome python
20
It is comma separated by a sequence of items and created without () and are immutable.
Example:-
def fun():
str=”geeksforgeeks”
x=20
return str;
str.x=fun ()
print(str)
print(x)
Output:-
geeksforgeeks
20
This list is like an array of items which are created using the square brackets. The lists are different from the tuples and are mutable.
Example:-
def fun ()
str=”geeksforgeeks”
x=20
return[str, x];
lists=fun ()
print(list)
Output:-
[‘geeksforgeeks’, 20]
The dictionary is same as other languages and the detail is explained by the example below.
Example:-
def fun ():
d=dict ();
d[‘str’] =”GeeksforGeeks”
d[‘x’] =20
return d
r=fun()
print(d)
Output:-
{‘x’:20,’str’:’GeeksforGeeks’}
It will create the getperson() and known function who can return the single variable and return multiple variables. The variables are stored from function call.
Example:-
def getperson ():
name=”sunny”
age=20
country=”India”
return name, age, country
name, age, country=getperson ()
print(name)
print(age)
print(country)
Output:-
sunny
20
India