Python function return multiple values

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.

A) using the tuple:-

def func(x):
y0=x+1
y1=x*3
y2=y0**3
return(y0, y1, y2)

B) using the dictionary:-

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}

C) using a class:-

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)

D) using a list:-

def func(x)
result=[x+1]
result.append(x*3)
result. append (y0**3)
return result

 

1) Example using generator:-

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.

2. Program using the object:-

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

3. Program using tuples:-

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

4. Program using a list:-

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]

5. Program using a Dictionary:-

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’}

6. The multiple returns:-

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

Additional Services : Refurbished Laptops Sales, Python Classes, Share Market Classes And SEO Freelancer in Pune, India