Sometimes you need a tiny function for just one small job, like "give me the second item" or "double this number". Writing a full def block for that feels like too much.
For these cases, Python has lambda functions: small, one-line functions that you can write right where you need them.
What is a Lambda Function?
A lambda function is a small anonymous function written in a single line. It can take any number of arguments but contains only one expression, whose value is returned automatically.
"Anonymous" simply means it doesn't need a name.
Syntax
lambda parameters: expressionlambdais the keyword.parametersare written without parentheses, separated by commas.expressionis evaluated and returned. You don't writereturn.
def vs lambda
These two functions do exactly the same thing:
def square(x):
return x * x
square_lambda = lambda x: x * x
print(square(5))
print(square_lambda(5))Output:
25
25Here's how the parts map to each other:
def square(x): lambda x: x * x
return x * x | |
| +-- the returned expression
+------- the parameterNote: Assigning a lambda to a name, like
square_lambda = lambda x: x * x, is shown here only for learning. Python's style guide (PEP 8) recommends usingdefwhen a function needs a name. Lambdas shine when passed directly to another function, as you'll see below.
Multiple Parameters and No Parameters
add = lambda a, b: a + b
print(add(3, 4))
full_name = lambda first, last: f"{first} {last}"
print(full_name("Virat", "Kohli"))
say_hello = lambda: "Hello!"
print(say_hello())Output:
7
Virat Kohli
Hello!Conditional Expressions in a Lambda
A lambda can contain only one expression, so you can't use an if statement. But you can use a conditional expression, which you learned earlier:
grade = lambda marks: "Pass" if marks >= 40 else "Fail"
print(grade(75))
print(grade(32))Output:
Pass
FailWhere Lambdas Are Actually Used
The real power of lambdas appears when a function accepts another function as an argument. In Python, functions are values, so you can pass them around like numbers or strings.
1. Sorting with key
The built-in sorted() function returns a new sorted list. Its key parameter takes a function that tells Python what to sort by:
words = ["banana", "kiwi", "apple", "fig"]
print(sorted(words)) # alphabetical
print(sorted(words, key=lambda w: len(w))) # by length
print(sorted(words, key=lambda w: w[-1])) # by last letterOutput:
['apple', 'banana', 'fig', 'kiwi']
['fig', 'kiwi', 'apple', 'banana']
['banana', 'apple', 'fig', 'kiwi']For each word, Python calls the lambda and sorts using the value it returns. If two items have the same key, they keep their original order, because Python's sort is stable.
A very common pattern is sorting pairs of data, like students and their marks:
students = [("Riya", 88), ("Arjun", 95), ("Meera", 72)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print(by_marks)Output:
[('Arjun', 95), ('Riya', 88), ('Meera', 72)]Here s is each (name, marks) pair, and s[1] is the marks.
2. max() and min() with key
students = [("Riya", 88), ("Arjun", 95), ("Meera", 72)]
topper = max(students, key=lambda s: s[1])
print(topper)
shortest = min(["Python", "C", "Java"], key=lambda w: len(w))
print(shortest)Output:
('Arjun', 95)
C3. map(): Apply a Function to Every Item
map(function, iterable) applies the function to each item. It returns a map object, so we wrap it in list() to see the results:
prices = [100, 250, 400]
with_gst = list(map(lambda p: p * 1.18, prices))
print(with_gst)
doubled = list(map(lambda n: n * 2, [1, 2, 3, 4]))
print(doubled)Output:
[118.0, 295.0, 472.0]
[2, 4, 6, 8]4. filter(): Keep Only Some Items
filter(function, iterable) keeps the items for which the function returns True:
numbers = [3, 8, 11, 14, 20, 25]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)
marks = [35, 67, 90, 22, 48]
passed = list(filter(lambda m: m >= 40, marks))
print(passed)Output:
[8, 14, 20]
[67, 90, 48]5. reduce(): Combine Everything into One Value
reduce() lives in the functools module. It repeatedly combines items two at a time until one value is left:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
print(product)Output:
120Step by step:
1 * 2 = 2
2 * 3 = 6
6 * 4 = 24
24 * 5 = 120For simple cases, built-ins like sum(), max() and min() are clearer than reduce().
Limitations of Lambda
Only one expression. No multiple lines, no loops, no
if/elifblocks.No statements like assignment (
x = 5),return, orpassinside it.Error messages show
<lambda>instead of a useful name, which makes debugging harder.Complex lambdas are hard to read. If you can't understand it in one glance, use
def.
Feature |
|
|
|---|---|---|
Name | Always has a name | Anonymous |
Body | Any number of statements | A single expression |
| Written explicitly | Automatic |
Docstring | Supported | Not supported |
Best for | Reusable or complex logic | Short, throwaway functions passed to other functions |
A Tricky Pitfall: Lambdas in a Loop
This one appears in interviews. What do you think this prints?
functions = []
for i in range(3):
functions.append(lambda: i)
for f in functions:
print(f())Output:
2
2
2Many people expect 0 1 2. The lambda doesn't store the value of i when it is created. It looks up i when it is called, and by then the loop has finished and i is 2. This is called late binding.
The fix is to capture the current value using a default argument, because default values are evaluated when the function is created:
functions = []
for i in range(3):
functions.append(lambda i=i: i)
for f in functions:
print(f())Output:
0
1
2Summary
A lambda is a small, anonymous, one-expression function:
lambda args: expression.The expression's value is returned automatically.
Lambdas are most useful as arguments to functions like
sorted(),max(),min(),map()andfilter().Use a conditional expression for simple choices inside a lambda.
If the logic is long, reused, or needs a name, use
definstead.
Use lambda for short, simple, one-time logic. For everything else, write a normal function.