Lambda Function (Anonymous Functions)
-
Learn how to create and use Lambda (anonymous) functions in Python.
What is a Lambda Function?
A lambda function is a small, anonymous function (function without a name).
👉 It can have any number of arguments, but only one expression.
Why Do We Use Lambda Functions?
Lambda functions are used to:
Write short and simple functions
Reduce code length
Improve readability for small tasks
Use functions only once
Work with map(), filter(), reduce()
Real-Life Example:
Sorting data, filtering values, quick calculations.Syntax of Lambda Function
lambda arguments : expression
Syntax Explanation
⚠️ No return keyword is used.
The result of the expression is returned automatically.Lambda vs Normal Function
Basic Lambda Function
This lambda function returns the square of a number.
square = lambda x: x * x
print(square(5))
Lambda with Multiple Arguments
This lambda function adds two numbers.
add = lambda a, b: a + b
print(add(10, 20))
Direct Lambda Function Call
This lambda function is called directly without storing in a variable.
print((lambda x: x + 10)(5))
Conditional Lambda Function
This lambda function checks whether a number is even or odd.
check = lambda n: "Even" if n % 2 == 0 else "Odd"
print(check(7))
Lambda with map() Function
What is map()?
map() applies a function to each item of a list.
Using Lambda with map()
This program squares each number in the list.
numbers = [1, 2, 3, 4]
result = list(map(lambda x: x * x, numbers))
print(result)
Lambda with filter() Function
What is filter()?
filter() selects items based on a condition.
Using Lambda with filter()
This program filters even numbers from the list.
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Lambda with reduce() Function
What is reduce()?
reduce() reduces a list to a single value.
(It is available in the functools module.)
Using Lambda with reduce()
This program finds the sum of all elements in the list.
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, numbers)
print(total)
Limitations of Lambda Functions
Only one expression
No statements (loops, try-except)
Less readable for complex logic