Returning Multiple Values in Python
Last Updated :
02 May, 2023
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class.
Python
class Test:
def __init__( self ):
self . str = "geeksforgeeks"
self .x = 20
def fun():
return Test()
t = fun()
print (t. str )
print (t.x)
|
Below are interesting methods for somebody shifting C++/Java world.
2) Using Tuple: A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are immutable. See this for details of tuple and list.
Python
def fun():
str = "geeksforgeeks"
x = 20
return str , x
str , x = fun()
print ( str )
print (x)
|
3) Using a list: A list is like an array of items created using square brackets. They are different from arrays as they can contain items of different types. Lists are different from tuples as they are mutable.
Python
def fun():
str = "geeksforgeeks"
x = 20
return [ str , x]
list = fun()
print ( list )
|
Output
['geeksforgeeks', 20]
4) Using a Dictionary: A Dictionary is similar to hash or map in other languages. See this for details of dictionary.
Python
def fun():
d = dict ();
d[ 'str' ] = "GeeksforGeeks"
d[ 'x' ] = 20
return d
d = fun()
print (d)
|
Output
{'x': 20, 'str': 'GeeksforGeeks'}
5) Using Data Class (Python 3.7+): In Python 3.7 and above the Data Class can be used to return a class with automatically added unique methods. The Data Class module has a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() in the user-defined classes.
Python3
from dataclasses import dataclass
@dataclass
class Book_list:
name: str
perunit_cost: float
quantity_available: int = 0
def total_cost( self ) - > float :
return self .perunit_cost * self .quantity_available
book = Book_list( "Introduction to programming." , 300 , 3 )
x = book.total_cost()
print (x)
print (book)
Book_list(name = 'Python programming.' ,
perunit_cost = 200 ,
quantity_available = 3 )
|
Output
900
Book_list(name='Introduction to programming.', perunit_cost=300, quantity_available=3)
6. Using ‘yield’
One alternative approach for returning multiple values from a function in Python is to use the yield keyword in a generator function. A generator function is a special type of function that returns an iterator object, which generates a sequence of values on the fly, one value at a time.
To return multiple values from a generator function, you can use the yield keyword to yield each value in turn. The generator function will then pause execution until the next value is requested, at which point it will resume execution and yield the next value. This process continues until the generator function completes execution or encounters a return statement.
Here is an example of how this can be done:
Python3
def get_values():
yield 42
yield 'hello'
yield [ 1 , 2 , 3 ]
result = get_values()
print ( next (result))
print ( next (result))
print ( next (result))
|
Output
42
hello
[1, 2, 3]
Time complexity: O(1) because it only performs a constant number of operations (yields) regardless of the size of the input.
Auxiliary space: O(1) because it only stores a constant number of variables (yielded values) in memory at any given time.
Reference: http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python
Please Login to comment...