Learn how to use Python lambda functions with this detailed guide. Discover syntax, examples, and use cases to enhance your programming skills.
Syntax:
The syntax of a lambda is
lambda arguments:express
Example #1: Add 10 Using Lambda in Python
Following code is used to write the function to add 10 in given number.
def add_ten(x)
return x + 10
above function can be written by the lamdba function in python.
add_ten = lambda x: x + 10
print(add_ten(5) # 15
Example #2: Multiply two numbers using lambda
use of lambda function to multiple two numbers
mul = lambda a, b : a * b
print(mul(2,4)) # 8
Example #3: Check Even Number
is_even = lambda x: x % 2 == 0
print(is_even(6)) # Output: True
Example #4: Immediately invoked function expression
(lambda x, y : x + y)(6,8) # 14
The lambda function above is defined and then immediately called with two arguments (6,8). it retuns the value 14, which is the sum of the arguments.
Example #5:
def multiply(x, y):
return x * y
# Using lambda function to call multiply
result = (lambda x, y: multiply(x, y))(5, 3)
print(result) # Output: 15
# Assigning lambda function to a variable
mult = lambda x, y: multiply(x, y)
result = mult(6, 2)
print(result) # Output: 12
Example #6:
lambda x, y : x + y
_(6,8) # 14
Note: In the interactive interpreter, the single underscore(_) is bound to the last expression evalued.
Python Tutorial: How to Use of Lambda function
Create a lambda function that adds two numbers.
Input: 3, 5
Expected Output: 8
Write a lambda function that multiplies two numbers.
Input: 4, 6
Expected Output: Output: 24
Python Tutorial: Multiplies two numbers
Create a lambda function to compute the cube of a number.
Input: 3
Expected Output: 27
Create a lambda function to compute the average of two numbers.
Input: 10, 20
Expected Output: 15.0