returns multiple values

Introduction:

  • In Python, Lambda Functions are designed to return the value of a single expression. However, you can return multiple values by packaging them into a single tuple or list.

Returning Multiple Values:

  • To return multiple values from a lambda function, use a tuple or a list. A tuple or a list can contain multiple values, but it is considered a single expression.

Syntax:

  • Using a tuple to return multiple values:

    python
    lambda x, y: (x + y, x - y, x * y)
    
  • Using a list to return multiple values:

    python
    lambda x, y: [x + y, x - y, x * y]
    

Examples:

  1. Calculator Lambda Function that Returns Multiple Values:
    • This example defines a lambda function assigned to a variable calculator. The lambda function takes two numbers, x and y, and returns their sum, difference, and product packed in a tuple.
    • Python Program:

      python
      calculator = lambda x, y: (x + y, x - y, x * y)
      
      # Call lambda function
      result = calculator(5, 4)
      print(result)
      
    • Output:

       
      (9, 1, 20)
      
  2. Unpacking Multiple Values Returned by Lambda Function into Individual Variables:
    • This example unpacks the values returned by the lambda function into individual variables.
    • Python Program:

      python
      calculator = lambda x, y: (x + y, x - y, x * y)
      
      # Call lambda function and unpack values into multiple variables
      addition, subtraction, multiplication = calculator(5, 4)
      print(f"Addition: {addition}")
      print(f"Subtraction: {subtraction}")
      print(f"Multiplication: {multiplication}")
      
    • Output:

       
      Addition: 9
      Subtraction: 1
      Multiplication: 20
      

Exercises:

  1. Return Multiple String Manipulations:
    • Define a lambda function that takes a string and returns its uppercase, lowercase, and reverse as a tuple.

      python
      string_operations = lambda s: (s.upper(), s.lower(), s[::-1])
      
      result = string_operations("Hello")
      print(result)  # Output: ('HELLO', 'hello', 'olleH')
      
  2. Return Multiple Results for Numbers:
    • Define a lambda function that takes a number and returns its square, cube, and square root as a tuple.

      python
      import math
      
      number_operations = lambda n: (n ** 2, n ** 3, math.sqrt(n))
      
      result = number_operations(9)
      print(result)  # Output: (81, 729, 3.0)
      

Summary:

  • In this tutorial, we learned how to return multiple values from a lambda function using a tuple or a list. Lambda functions are useful for concise and efficient operations. Practice using lambda functions with multiple return values to get comfortable with these powerful tools in your Python programs!