In Python, a lambda function is a small, anonymous function defined using the lambda
keyword. It can take any number of arguments but can only have a single expression. The expression is evaluated and returned when the function is called.
Lambda functions are often used for short, simple operations where defining a full function using def
might feel unnecessary.
Syntax:
lambda arguments: expression
arguments
: Input to the lambda function (can be multiple arguments, separated by commas).
expression
: The operation that will be performed and returned.
Example 1: Basic Lambda Function
# A lambda function that adds 20 to a given number
add = lambda x: x + 20
print(add(10)) # Output: 30
Explanation: The lambda function takes one argument (x
) and returns x + 20
.
Example 2: Lambda with Multiple Arguments
# A lambda function that adds two numbers
add = lambda a, b: a + b
print(add(5, 7)) # Output: 12
Explanation: The lambda function takes two arguments (a
and b
) and returns their sum.
Example 3: Using Lambda with map()
The map()
function applies a function to every item in an iterable (like a list). You can use a lambda function here to apply a quick transformation.
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Output: [1, 4, 9, 16, 25]
Explanation: The lambda function squares each number in the numbers
list.
Example 4: Using Lambda with filter()
The filter()
function filters elements from an iterable based on a condition provided by a lambda function.
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Output: [2, 4]
Explanation: The lambda function filters out even numbers from the list.
Example 5: Lambda with Default Arguments
Just like regular functions, lambda functions can have default arguments.
multiply = lambda a, b=2: a * b
print(multiply(3)) # Output: 6 (3 * 2)
print(multiply(3, 4)) # Output: 12 (3 * 4)
When to Use Lambda Functions:
When you need a small, simple function that is used only once or for a short time.
When passing a function as an argument to higher-order functions like sorted()
, map()
, or filter()
.
Limitations:
Lambda functions are restricted to a single expression and cannot contain complex logic.
They are often used for simple operations but may reduce code readability if overused.