returnIntermediate Examples

Exits a function and optionally sends a value back to the caller

Returning multiple values

Using tuples to return several values at once.

python
def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {lo}, Max: {hi}")

def stats(data):
    n = len(data)
    mean = sum(data) / n
    variance = sum((x - mean) ** 2 for x in data) / n
    return {"mean": mean, "variance": variance, "count": n}

result = stats([10, 20, 30, 40, 50])
print(result)
Expected Output
Min: 1, Max: 9
{'mean': 30.0, 'variance': 200.0, 'count': 5}

Python can return multiple values as a tuple (with implicit packing). You can also return dicts or named tuples for clarity.

Return in nested contexts

How return interacts with loops and try/finally.

python
def find_in_matrix(matrix, target):
    for i, row in enumerate(matrix):
        for j, val in enumerate(row):
            if val == target:
                return (i, j)
    return None

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(find_in_matrix(m, 5))
print(find_in_matrix(m, 10))

# return with finally
def tricky():
    try:
        return "from try"
    finally:
        print("finally runs before return!")

result = tricky()
print(f"Got: {result}")
Expected Output
(1, 1)
None
finally runs before return!
Got: from try

return exits from the innermost function, even from nested loops. finally blocks still execute before the return completes.

Want to try these examples interactively?

Open Intermediate Playground