A lambda function is a small anonymous (unnamed) function in Python.
It is used for short, simple operations that can be written in a single line.
Lambda functions are often used when a function is needed temporarily.
SYNTAX OF LAMBDA FUNCTION
lambda arguments: expression
• lambda is the keyword
• Arguments are inputs (like parameters)
• Expression is the value that will be returned automatically
Note: Lambda functions do not use the return keyword. The result of the expression is returned automatically.
EXAMPLE 1: SIMPLE LAMBDA FUNCTION
add = lambda a, b: a + b
print(add(5, 3))
Output:
8
This works similar to:
def add(a, b):
return a + b
EXAMPLE 2: LAMBDA WITH ONE ARGUMENT
square = lambda x: x * x
print(square(4))
Output:
16
LAMBDA WITH IF-ELSE (CONDITIONAL EXPRESSION)
check_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check_even(5))
Output:
Odd
USING LAMBDA WITH BUILT-IN FUNCTIONS
Lambda functions are commonly used with functions like map(), filter(), and sorted().
Example with map()
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, numbers))
print(squares)
Example with filter()
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
WHEN TO USE LAMBDA FUNCTIONS
• For short, simple operations
• When passing a function as an argument
• When you need a quick temporary function
LIMITATIONS OF LAMBDA FUNCTIONS
• Can only contain a single expression
• Cannot include multiple statements
• Less readable for complex logic
WHY LAMBDA FUNCTIONS ARE IMPORTANT
• Make code shorter and cleaner
• Useful in functional programming
• Help write concise and efficient programs
Understanding lambda functions helps you write compact and professional Python code.