Returning Multiple Values in Python
In Python, a function can return more than one value at a time using commas. These values are usually returned as a tuple. This is useful when a function needs to give back several related results together.
Lets explore different ways to do it.
Using Tuple
Tuple is a group of values separated by commas. Python automatically packs the values into a tuple, which can then be unpacked into variables.
def fun():
return "geeksforgeeks", 20
s, x = fun()
print(s)
print(x)
Output
geeksforgeeks 20
Explanation: fun() returns two values as a tuple, which are unpacked into s and x and then printed.
Using Data Class
Data class is a special type of class used to store multiple related values. It automatically creates useful methods like __init__() and __repr__(), so it's easy to create and return multiple values in a clean, readable way.
from dataclasses import dataclass
@dataclass
class Student:
name: str
marks: int
def get_student():
return Student("Alice", 85)
student = get_student()
print(student.name)
print(student.marks)
Output
Alice 85
Explanation: get_student() returns a Student dataclass object with multiple values, which can be accessed using dot notation like student.name and student.marks.
Using Dictionary
Dictionary stores data in key-value pairs. It can be used to return multiple values from a function by assigning each value a key, making the result easy to read and access.
def fun():
d = {"str": "GeeksforGeeks", "x": 20}
return d
d = fun()
print(d)
Output
{'x': 20, 'str': 'GeeksforGeeks'}
Explanation: fun() creates a dictionary with two key-value pairs and returns it, which is then printed.
Using Object
An object created from a class can hold multiple values as attributes. A function can return an object to group and return several related values together.
class Info:
def __init__(self):
self.name = "Alice"
self.age = 25
def get_info():
return Info()
person = get_info()
print(person.name)
print(person.age)
Output
Alice 25
Explanation:
- get_info() returns an object of the Info class containing two values name and age.
- values are accessed using dot notation person.name and person.age.
Using List
List is an ordered collection of items, created using square brackets []. A list can be used to return multiple values from a function, especially when the number of values is fixed.
def fun():
l = ["geeksforgeeks", 20]
return l
d = fun()
print(d)
Output
['geeksforgeeks', 20]
Explanation: fun() returns a list with two values, which is stored in data and then printed.
Related Articles: