What Is a Lambda Function in Python? (5 Real Examples)
Video: What Is a Lambda Function in Python? (5 Real Examples) by CelesteAI
A lambda is just an unnamed function. One expression, one line, no def, no name. That’s the whole definition.
The reason you see lambdas everywhere in real Python code is that the standard library and pandas have a bunch of higher-order functions — sorted, filter, max, .apply, .map — that take a function as an argument and call it many times. When the function you want to pass is tiny and one-off, writing a full def for it feels heavy. A lambda lets you write the function inline at the point you need it.
This post walks five real cases plus the gotcha that catches every beginner.
The basics — a lambda is just an unnamed function
square = lambda x: x * x
square(5) # 25
That’s identical to:
def square(x):
return x * x
Same calling convention. Same behavior. Same bytecode, near enough. The only differences are that a lambda has no name (well, here we assigned it to one, but that defeats the point) and is meant to be written inline as part of a larger expression. If you’re writing name = lambda ..., you probably wanted def name(...) instead.
1. sorted(key=lambda) — the canonical case
You have a list of tuples and want to sort by the second element. sorted() takes a key parameter that’s a function called on each element. Lambda lets you write that function inline:
positions = [("AAPL", 185.50), ("MSFT", 415.30), ("GOOG", 142.40)]
sorted(positions, key=lambda x: x[1], reverse=True)
# [("MSFT", 415.30), ("AAPL", 185.50), ("GOOG", 142.40)]
Defining a named def get_price(x): return x[1] for a one-line key would be noise. Lambda is the right tool.
2. pandas .apply(lambda) — per-cell transform
df["formatted"] = df["price"].apply(lambda p: f"${p:,.2f}")
df["bucket"] = df["price"].apply(lambda p: "big" if p > 200 else "small")
.apply calls the lambda once per cell. The lambda receives one value, returns one value, pandas stitches them into a new Series. Conditional expressions (if/else as an expression, not a statement) work because they ARE a single expression.
3. filter(lambda) — keep elements that match
big = list(filter(lambda x: x[1] > 200, positions))
# [("MSFT", 415.30)]
filter walks the iterable, calls the lambda on each item, keeps the ones where the result is truthy. Pairs perfectly with lambda for one-off predicates.
4. max(key=lambda) — picking by a custom key
priciest = max(positions, key=lambda x: x[1])
# ("MSFT", 415.30)
Same key pattern as sorted. So is min().
5. The limit — one expression, no statements
This is the gotcha. A lambda body is exactly ONE expression. No statements. No return keyword. No multi-line bodies.
All of these are SyntaxError:
bad = lambda x: print(x); return x # no return keyword in lambda
bad = lambda x: if x > 0: x else: -x # no statements
bad = lambda x: # no multi-line bodies
cleaned = x.strip()
return cleaned
The moment your function needs more than one expression — an assignment, a for loop, a multi-statement block — switch to def:
def clean_ticker(raw: str) -> str:
cleaned = raw.strip().upper()
return cleaned or "UNKNOWN"
Don’t try to cram multiple things into a lambda with ; or deeply-nested ternaries. The point of lambda is that it’s tiny and readable. If yours isn’t, that’s the signal.
Lambda is not faster than def
This comes up. Lambda and def compile to essentially the same bytecode and call into the same machinery. There’s no performance difference worth measuring.
Choose based on readability:
- Trivial, used once → lambda
- Multi-line, named, reused → def
Want the deeper dive?
Common Questions Ep 10 — .map vs .apply vs .applymap leans on lambdas in every pandas example. If you want to see lambdas in their natural habitat — passed into higher-order pandas methods — that episode is the next one to watch.