How to Return Multiple Values in Python?

Estimated read time 2 min read

In Python, you can return multiple values from a function by using tuples, lists, or other data structures. Here are a few approaches:

  1. Tuples: You can pack multiple values into a tuple and return the tuple. To create a tuple, you can use parentheses or simply separate the values with commas. Here’s an example:
def get_values():
    value1 = 10
    value2 = "hello"
    return value1, value2

result = get_values()
print(result)  # Output: (10, 'hello')

In the example above, the get_values() function returns a tuple (value1, value2). The values can be unpacked into separate variables, or you can use indexing to access individual values.

  1. Lists: Similar to tuples, you can pack multiple values into a list and return the list. Here’s an example:
def get_values():
    values = [10, "hello"]
    return values

result = get_values()
print(result)  # Output: [10, 'hello']

In this case, the get_values() function returns a list [10, "hello"].

  1. Dictionaries: Another option is to use dictionaries to return multiple values, associating each value with a specific key. Here’s an example:
def get_values():
    values = {'value1': 10, 'value2': "hello"}
    return values

result = get_values()
print(result)  # Output: {'value1': 10, 'value2': 'hello'}

In the example above, the get_values() function returns a dictionary {'value1': 10, 'value2': 'hello'}.

You can choose the approach that best fits your needs depending on the context and the way you want to handle the returned values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply