Return multiple values from a function

Introduction:

  • In Python, you can return multiple values from a function using the return statement. The values must be separated by commas.

Syntax:

python
def someFunction():
    # some code
    return a, b, c
  • Replace a, b, and c with the values you want to return.

Example:

  • Let's create a swap function that takes two arguments, swaps their values, and returns both of them.

Python Program:

python
# Function that returns multiple values
def swap(x, y):
    temp = x
    x = y
    y = temp
    return x, y

# Take two values
a = 10
b = 20
print(f'\nBefore Swap - (a, b)  : ({a}, {b})')

# Swap a, b
a, b = swap(a, b)
print(f'\nAfter  Swap - (a, b)  : ({a}, {b})')

Output:

 
Before Swap - (a, b)  : (10, 20)

After  Swap - (a, b)  : (20, 10)

Explanation:

  • The swap function takes two arguments, x and y.
  • It swaps their values and returns both x and y.
  • The returned values are then unpacked back into a and b.

Exercises:

  1. Return Multiple Values from a Function:
    • Write a function calculate that takes two numbers and returns their sum, difference, and product.

      python
      def calculate(x, y):
          sum = x + y
          difference = x - y
          product = x * y
          return sum, difference, product
      
      # Test the function
      result = calculate(10, 5)
      print(result)  # Output: (15, 5, 50)
      
  2. Return Tuple from a Function:
    • Write a function get_student_details that takes a student's name, age, and grade, and returns them as a tuple.

      python
      def get_student_details(name, age, grade):
          return name, age, grade
      
      # Test the function
      student = get_student_details("Alice", 14, "9th")
      print(student)  # Output: ('Alice', 14, '9th')
      
  3. Unpack Multiple Return Values:
    • Write a function split_name that takes a full name and returns the first name and last name separately. Unpack the returned values into separate variables.

      python
      def split_name(full_name):
          first_name, last_name = full_name.split()
          return first_name, last_name
      
      # Test the function
      first, last = split_name("John Doe")
      print(f'First Name: {first}, Last Name: {last}')  # Output: First Name: John, Last Name: Doe
      

Summary:

  • In this tutorial, we learned how to return multiple values from a function using the return statement. This allows you to get multiple results from functions and use them elsewhere in your program. Practice writing functions with multiple return values to become proficient in this essential programming concept!