Lambda in Python
In Python, lambda is an anonymous function (a function without a name). It is used for small, one-line functions where defining a full function using def would be unnecessary.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x ** 2
print(square(5)) # Output: 25
Lambda functions are commonly used with higher-order functions like map(), filter(), and reduce().
Higher-Order Functions
A higher-order function is a function that either:
- Takes another function as an argument
- Returns a function as output
Examples of Higher-Order Functions:
- Using
map()with lambda
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
- Using
filter()with lambda
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4]
- Using
reduce()with lambda (fromfunctoolsmodule)
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
Higher-order functions make Python code more concise, readable, and functional-programming-friendly. 🚀
Comments
Post a Comment