Lambda Functions (Anonymous Functions) in Python - DJC
Lambda functions are small, unnamed functions defined in a single line. They are useful for simple operations, especially when used with functions like map
, filter
, or sorted
.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x ** 2
print(square(4)) # Output: 16
With map and filter:
numbers = [1, 2, 3, 4]
doubles = list(map(lambda x: x * 2, numbers)) # [2, 4, 6, 8]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
They are not recommended for complex functions, as they can reduce code readability.