In Python, there are several ways to return multiple values from a function. Here are the most common methods:
1. Using a Tuple (Most Common)
You can return multiple values by grouping them in a tuple. This is the most common way:
def get_coordinates():
x = 10
y = 20
return x, y
coordinates = get_coordinates()
print(coordinates) # Output: (10, 20)
# You can also unpack the tuple into separate variables
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
2. Using a List
You can return multiple values as a list if you prefer a mutable collection:
def get_coordinates():
x = 10
y = 20
return [x, y]
coordinates = get_coordinates()
print(coordinates) # Output: [10, 20]
# You can also unpack the list into separate variables
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
3. Using a Dictionary
Returning a dictionary is useful when you want to return values with keys, making the return values more descriptive:
def get_coordinates():
return {"x": 10, "y": 20}
coordinates = get_coordinates()
print(coordinates) # Output: {'x': 10, 'y': 20}
# Access individual values by key
print(coordinates['x']) # Output: 10
print(coordinates['y']) # Output: 20
4. Using a Namedtuple
namedtuple
provides a way to return multiple values with names, similar to a dictionary, but with the performance benefits of a tuple:
from collections import namedtuple
def get_coordinates():
Coordinates = namedtuple('Coordinates', ['x', 'y'])
return Coordinates(10, 20)
coordinates = get_coordinates()
print(coordinates) # Output: Coordinates(x=10, y=20)
# Access individual values by name
print(coordinates.x) # Output: 10
print(coordinates.y) # Output: 20
5. Using a Custom Class
If you need more structure or want to return an object with methods, you can define a custom class:
class Coordinates:
def __init__(self, x, y):
self.x = x
self.y = y
def get_coordinates():
return Coordinates(10, 20)
coordinates = get_coordinates()
print(coordinates.x) # Output: 10
print(coordinates.y) # Output: 20
6. Returning Multiple Values Directly (Python 3.8+)
Starting from Python 3.8, you can use the "Walrus operator" (:=
) in return statements:
def get_coordinates():
return (x := 10), (y := 20)
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
These methods give you the flexibility to choose the best approach depending on your specific needs in the code.
Discussion