Lambda Functions in Python
#Lambda Functions in Python
Lambda functions, also known as anonymous functions, are a powerful feature in Python that allow you to write small, concise, and inline functions without formally defining them using def
. They are often used for short tasks where creating a full function would be unnecessary.
A lambda function in Python is a small, unnamed function defined using the lambda
keyword. Unlike regular functions created with def
, lambda functions are limited to a single expression.
Syntax:
lambda arguments: expression
lambda
→ keyword to define a lambda function
arguments
→ input values
expression
→ the operation to be performed and returned
# Regular function
def square(x):
return x * x
# Equivalent lambda function
square_lambda = lambda x: x * x
print(square_lambda(5)) # Output: 25
Lambda functions are useful when:
You need a quick one-line function.
You want to pass a function as an argument to higher-order functions (like map
, filter
, reduce
).
You want to avoid clutter in your code.
map()
, filter()
, and reduce()
map()
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
filter()
numbers = [10, 15, 20, 25, 30]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [10, 20, 30]
reduce()
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120
Lambda functions can have multiple arguments but only one expression.
They return the result of the expression automatically.
They are best suited for short-term use within functions.
For complex logic, prefer regular functions (def
).
Concise and readable code
Perfect for inline operations
Useful in functional programming approaches
Cannot contain multiple expressions or statements
Less readable for complex logic
No docstrings (harder to document)
Lambda functions in Python are a handy tool for writing clean and efficient code. While they should not replace standard functions for complex tasks, they shine in scenarios where short, inline functions improve readability and reduce boilerplate.