Python Functions
Python Lambda Functions
A lambda function is a small, anonymous function written in a single line using the lambda keyword — perfect for short, throwaway logic you need just once, often as an argument to another function.
Lambda Syntax
A lambda function has the form lambda arguments: expression. It can take any number of arguments but must contain exactly one expression, whose result is automatically returned — there is no return keyword and no function name required.
square = lambda x: x * x
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7The line above is equivalent to writing def square(x): return x * x — lambda is just a shorter, inline way to define a simple function.
Using Lambda with sorted()
A very common use of lambda is as the key argument for sorted(), telling Python exactly what to sort by without writing a separate named function.
students = [("Aarav", 82), ("Diya", 91), ("Kabir", 76)]
ranked = sorted(students, key=lambda s: s[1], reverse=True)
print(ranked)
# [('Diya', 91), ('Aarav', 82), ('Kabir', 76)]Using Lambda with map() and filter()
lambda pairs naturally with map() (to transform every item in an iterable like a list) and filter() (to keep only items that satisfy a condition).
nums = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda x: x * x, nums))
print(squares) # [1, 4, 9, 16, 25, 36]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6]Limits of Lambda
Lambda functions are intentionally limited — they cannot contain statements like if/else blocks (only a conditional expression), loops, multiple lines, or docstrings. If your logic needs more than one expression, write a normal function with def instead.
- Only one expression is allowed — no statements, no multiple lines.
- No docstrings and no name, which makes debugging harder for complex logic.
- Best kept short — if it needs a comment to explain it, use a regular function.
Avoid assigning a lambda to a variable just to reuse it, like formula = lambda x: x*2 — in that case a normal def is clearer and gives better error messages.
