How to Return a Tuple in Python?

Estimated read time 2 min read

In Python, you can return a tuple from a function by enclosing the values within parentheses. Here’s an example:

def get_tuple():
    value1 = "Hello"
    value2 = "World"
    return value1, value2

result = get_tuple()
print(result)  # Output: ("Hello", "World")

In this example, the get_tuple() function assigns the values "Hello" and "World" to the variables value1 and value2, respectively. The return statement then returns these values as a tuple by enclosing them within parentheses.

When the function is called, the returned tuple is stored in the result variable. Printing result displays ("Hello", "World"), indicating that a tuple containing the values "Hello" and "World" has been returned.

You can also explicitly create a tuple using the tuple() constructor and return it:

def get_tuple():
    value1 = "Hello"
    value2 = "World"
    return tuple([value1, value2])

result = get_tuple()
print(result)  # Output: ("Hello", "World")

In this case, the tuple() constructor is called with a list [value1, value2] as an argument. This list is converted into a tuple, which is then returned from the function.

Both approaches allow you to return multiple values from a function as a tuple in Python. The returned tuple can be accessed and used like any other tuple, allowing you to extract individual values or perform operations on the tuple as a whole.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply