In Python, a Lambda Function is a small, anonymous function that is defined without a name. While standard functions are defined using the def keyword, anonymous functions are defined using the lambda keyword.
They are often referred to as "throwaway" functions because they are frequently used for short periods where a full function definition would be overkill.
Anonymous: They do not have a name (unless assigned to a variable).
Single Expression: They can only contain a single expression. You cannot have multiple lines of logic or complex statements (like if-else blocks with multiple branches) inside them.
Implicit Return: The result of the expression is automatically returned; you do not use the return keyword.
Inline: They are usually defined at the exact location where they are needed.
The syntax is very concise: lambda arguments : expression
Here is a comparison of a function that adds 10 to a number.
Standard Way:
def add_ten(x): return x + 10 print(add_ten(5)) # Output: 15
Lambda Way:
add_ten_lambda = lambda x : x + 10 print(add_ten_lambda(5)) # Output: 15
Lambda functions can take any number of arguments, but they must still consist of only one expression.
# Multiply two numbers multiply = lambda a, b : a * b print(multiply(10, 6)) # Output: 60
Lambda functions shine when used as arguments to Higher-Order Functions (functions that take other functions as input).
Used to extract elements from an iterable that meet a condition.
numbers = [1, 2, 3, 4, 5, 6] # Get only even numbers evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # Output: [2, 4, 6]
Used to apply a specific operation to every item in an iterable.
# Square every number in the list squares = list(map(lambda x: x**2, numbers)) print(squares) # Output: [1, 4, 9, 16, 25, 36]
Complexity: If the logic requires multiple lines or complex error handling, use def.
Readability: If the lambda makes the code harder to understand for other developers, a named function is better.
Reusability: If you need to use the same logic in five different places, define it once with def.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION