Open In App

Returning Multiple Values in Python

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# A Python program to return multiple
# values from a method using class
class Test:
    def __init__(self):
        self.str = "geeksforgeeks"
        self.x = 20
 
# This function returns an object of Test
def fun():
    return Test()
     
# Driver code to test above method
t = fun()
print(t.str)
print(t.x)


Output

geeksforgeeks
20

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




# A Python program to return multiple
# values from a method using tuple
 
# This function returns a tuple
def fun():
    str = "geeksforgeeks"
    x = 20
    return str, x # Return tuple, we could also
                    # write (str, x)
 
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)


Output

geeksforgeeks
20

  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




# A Python program to return multiple
# values from a method using list
 
# This function returns a list
def fun():
    str = "geeksforgeeks"
    x = 20
    return [str, x]
 
# Driver code to test above method
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




# A Python program to return multiple
# values from a method using dictionary
 
# This function returns a dictionary
def fun():
    d = dict();
    d['str'] = "GeeksforGeeks"
    d['x'] = 20
    return d
 
# Driver code to test above method
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
         
    # function to calculate total cost    
    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 the total cost
# of the book
print(x)
 
# print book details
print(book)
 
# 900
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]
 
# Test code
result = get_values()
print(next(result))  # should print 42
print(next(result))  # should print 'hello'
print(next(result))  # should print [1, 2, 3]


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



Previous Article
Next Article

Similar Reads

Python | Returning index of a sorted list
Sort a list in python and then return the index of elements in sorted order. Examples: Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, 5] and their index as [2, 0, 1, 3, 4] Input : [6, 4, 7, 8, 1] Output : [4, 1, 0, 2, 3] After sorting the list becomes [1, 4, 6, 7, 8] and their index as [4, 1, 0, 2, 3]. Meth
3 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
3 min read
Returning distinct rows in SQLAlchemy with SQLite
In this article, we are going to see how to return distinct rows in SQLAlchemy with SQLite in Python. Installation SQLAlchemy is available via pip install package. pip install sqlalchemy However, if you are using flask you can make use of its own implementation of SQLAlchemy. It can be installed using - pip install flask-sqlalchemyCreating Database
3 min read
Python | Assign multiple variables with list values
We generally come through the task of getting certain index values and assigning variables out of them. The general approach we follow is to extract each list element by its index and then assign it to variables. This approach requires more line of code. Let's discuss certain ways to do this task in compact manner to improve readability. Method #1
4 min read
Python - Pairs with multiple similar values in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we need to keep the dictionaries which are having similar key's value in other dictionary. This is a very specific problem. This can have applications in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehensi
4 min read
How to input multiple values from user in one line in Python?
For instance, in C we can do something like this: C/C++ Code // Reads two values in one line scanf("%d %d", &x, &y) One solution is to use raw_input() two times. C/C++ Code x, y = input(), input() Another solution is to use split() C/C++ Code x, y = input().split() Note that we don't have to explicitly specify spli
2 min read
Python Yield Multiple Values
In Python, yield is a keyword that plays a very crucial role in the creation of a generator. It is an efficient way to work with a sequence of values. It is a powerful and memory-efficient way of dealing with large values. Unlike a return statement which terminates the function after returning a value, yield produces and passes a series of values.
4 min read
Filtering a List of Dictionary on Multiple Values in Python
Filtering a list of dictionaries is a common task in programming, especially when dealing with datasets. Often, you may need to extract specific elements that meet certain criteria. In this article, we'll explore four generally used methods for filtering a list of dictionaries based on multiple values, providing code examples in Python. Filtering A
4 min read
Search for Value in the Python Dictionary with Multiple Values for a Key
In Python, searching for a value in a dictionary with multiple values for a key involves navigating through key-value pairs efficiently. This scenario often arises when a key maps to a list, tuple, or other iterable as its value. In this article, we will explore four different approaches to searching for value in the dictionary with multiple values
4 min read
Python - Replace K with Multiple values
Sometimes, while working with Python Strings, we can have a problem in which we need to perform replace of single character/work with particular list of values, based on occurrence. This kind of problem can have application in school and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_str = '* is *
5 min read
Article Tags :
Practice Tags :