with two arguments
Introduction:
- A lambda function in Python allows you to create small, anonymous functions that can take any number of arguments. Lambda functions are handy for short operations that you don't want to define using the standard
defkeyword.
Syntax:
To define a lambda function with two arguments, specify the parameters after the
lambdakeyword, separated by commas, followed by the function body:pythonlambda x, y: x * y
Examples:
- Find the Product of Two Numbers:
This example defines a lambda function that takes two arguments,
xandy, and returns their product.pythonproduct = lambda x, y: x * y num1 = 5 num2 = 3 result = product(num1, num2) print(f"Product of {num1} and {num2} is {result}.")Output:
Product of 5 and 3 is 15.
- Lambda Function to Check If Two Numbers Are Even:
This example defines a lambda function that takes two arguments,
xandy, and returnsTrueif both numbers are even, otherwise returnsFalse.pythonbothEven = lambda x, y: x % 2 == 0 and y % 2 == 0 num1 = 8 num2 = 14 if bothEven(num1, num2): print("Both the numbers are even.") else: print("Both the numbers are not even.")Output:
Both the numbers are even.
Exercises:
- Sum of Two Numbers:
Define a lambda function that takes two arguments and returns their sum.
pythonsum = lambda x, y: x + y print(sum(10, 5)) # Output: 15
- Greater Number:
Define a lambda function that takes two arguments and returns the greater of the two.
pythongreater = lambda x, y: x if x > y else y print(greater(10, 15)) # Output: 15
- Difference of Two Numbers:
Define a lambda function that takes two arguments and returns their difference.
pythondifference = lambda x, y: x - y print(difference(10, 5)) # Output: 5
Summary:
- In this tutorial, we learned how to define a lambda function with two arguments in Python. Lambda functions are useful for short, simple operations that you want to define quickly and use immediately. Practice writing lambda functions with different operations to get comfortable using them in your Python programs!