Alternatives for returning multiple values from a Python function
- Using a tuple:
def multiple_values():
value1 = 5
value2 = 10
return value1, value2
result = multiple_values()
print(result) # (5, 10)
Watch a video course
Python - The Practical Guide
- Using a list:
def multiple_values():
value1 = "Hello"
value2 = "World"
return [value1, value2]
result = multiple_values()
print(result) # ["Hello", "World"]
- Using a dictionary:
def multiple_values():
value1 = "key1"
value2 = "value1"
value3 = "key2"
value4 = "value2"
return {value1: value2, value3: value4}
result = multiple_values()
print(result) # {"key1": "value1", "key2": "value2"}
- Using an object:
class MultipleValues:
def __init__(self, value1, value2):
self.value1 = value1
self.value2 = value2
def multiple_values():
value1 = "apple"
value2 = "orange"
return MultipleValues(value1, value2)
result = multiple_values()
print(result.value1) # "apple"
print(result.value2) # "orange"