Python Lambda
A lambda function in Python is a small, anonymous (nameless) function defined with the lambda keyword. It can take any number of arguments, but can have only one expression, which is evaluated and returned automatically.
1. Basic Lambda Syntax
The syntax is lambda arguments : expression. Here is a simple example that adds 10 to a given number:
add_ten = lambda x: x + 10
print(add_ten(5)) # Output: 15
2. Lambda with Multiple Arguments
You can pass multiple arguments separated by commas before the colon:
multiply = lambda a, b: a * b
print(multiply(6, 7)) # Output: 42
3. Lambda Inside Another Function
Lambda functions are often used inside regular functions to create customized helper functions on the fly:
def multiplier(n):
return lambda x: x * n
doubler = multiplier(2)
tripler = multiplier(3)
print(doubler(10)) # Output: 20
print(tripler(10)) # Output: 30
4. Using Lambda with map(), filter() & sorted()
Lambda shines when passed as a short callback function to built-in functions like map(), filter(), and sorted():
nums = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda n: n ** 2, nums))
evens = list(filter(lambda n: n % 2 == 0, nums))
students = [("Rohan", 85), ("Ananya", 92), ("Vikram", 78)]
by_score = sorted(students, key=lambda item: item[1], reverse=True)
print("Squares:", squares)
print("Evens:", evens)
print("Sorted by score:", by_score)
Tip: Keep lambda functions short and readable. If your logic requires multiple statements or complex conditions, use a standard
def function instead.