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:
pythonlambda x, y: (x + y, x - y, x * y)Using a list to return multiple values:
pythonlambda x, y: [x + y, x - y, x * y]
Examples:
- Calculator Lambda Function that Returns Multiple Values:
- This example defines a lambda function assigned to a variable
calculator. The lambda function takes two numbers,xandy, and returns their sum, difference, and product packed in a tuple. Python Program:
pythoncalculator = lambda x, y: (x + y, x - y, x * y) # Call lambda function result = calculator(5, 4) print(result)Output:
(9, 1, 20)
- This example defines a lambda function assigned to a variable
- 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:
pythoncalculator = 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:
- Return Multiple String Manipulations:
Define a lambda function that takes a string and returns its uppercase, lowercase, and reverse as a tuple.
pythonstring_operations = lambda s: (s.upper(), s.lower(), s[::-1]) result = string_operations("Hello") print(result) # Output: ('HELLO', 'hello', 'olleH')
- Return Multiple Results for Numbers:
Define a lambda function that takes a number and returns its square, cube, and square root as a tuple.
pythonimport 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!