A lambda function is a small anonymous function in Python. It can take any number of arguments but can have only one expression.
A lambda function is a function created using the lambda keyword instead of the def keyword.
Basic syntax:
lambda arguments : expression
The expression is evaluated and its result is automatically returned.
square = lambda x: x * x
print(square(5))
Here, x is the parameter and x * x is the expression.
Normal function:
def square(x):
return x * x
print(square(5))
Lambda function:
square = lambda x: x * x
print(square(5))
Both functions produce the same result. The lambda version is shorter.
double = lambda x: x * 2
print(double(10))
add = lambda a, b: a + b
print(add(10, 20))
A lambda function can accept multiple arguments.
calculate = lambda a, b, c: a + b + c
print(calculate(10, 20, 30))
subtract = lambda a, b: a - b
print(subtract(20, 8))
multiply = lambda a, b: a * b
print(multiply(5, 6))
divide = lambda a, b: a / b
print(divide(20, 4))
A lambda function can contain a conditional expression.
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(10))
print(check(7))
maximum = lambda a, b: a if a > b else b
print(maximum(15, 10))
length = lambda text: len(text)
print(length("Python"))
Lambda functions can also be used with list elements.
numbers = [1, 2, 3, 4, 5]
square = lambda x: x * x
for n in numbers:
print(square(n))
The map() function applies a function to every item in an iterable.
Lambda functions are commonly used with map().
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
The filter() function selects items based on a condition.
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Lambda functions can be used as a key for sorting.
students = [
("Amit", 75),
("Ravi", 90),
("Neha", 82)
]
result = sorted(students, key=lambda x: x[1])
print(result)
Here, x[1] represents the marks of each student.
students = [
("Amit", 75),
("Ravi", 90),
("Neha", 82)
]
result = sorted(
students,
key=lambda x: x[1],
reverse=True
)
print(result)
A lambda function can be passed as an argument to another function.
def calculate(func, number):
return func(number)
result = calculate(lambda x: x * 2, 10)
print(result)
calculate = lambda a, b: (a + b) * 2
print(calculate(5, 10))
lambda keyword.map(), filter() and sorted().numbers = [10, 15, 20, 25, 30]
greater_than_20 = list(
filter(lambda x: x > 20, numbers)
)
print(greater_than_20)
map() and filter().def.lambda arguments: expression.map(), filter() and sorted().def when the logic becomes complex.Question: Which keyword is used to create a lambda function in Python?