Lambda Functions
Learn how to write compact, one-line anonymous functions with lambda, and discover exactly when they make your code cleaner — and when they don't.
You already know how to define a function with def. But sometimes you need a tiny, throwaway function — one so small that giving it a name and a whole block of code feels like overkill. That's where lambda functions come in.
A lambda is a way to write a simple function in a single line, right where you need it. Think of it as a sticky note: perfect for a quick job, not meant to hang on the wall forever.
See it in action
— step through the idea, then dive into the details below.Functions Without a Name
A lambda is a tiny, one-line function you write right where you need it — no def, no name, no ceremony. Think of it as a sticky note instead of a formal memo.
#The Basic Syntax
The syntax looks a little different from def, but it follows a simple pattern:
lambda parameters: expression
- `lambda` — the keyword that starts it
- parameters — the inputs (just like a regular function's arguments)
- expression — a single calculation or value to return (no
returnkeyword needed)
# A regular function
def double(x):
return x * 2
# The exact same thing as a lambda
lambda x: x * 2Lambda as a sticky note
Imagine you need to leave a quick note for someone: "multiply by 2". You wouldn't write a formal memo — you'd scribble it on a sticky note. A lambda is that sticky note. It's a tiny, in-place function for a task you need right now, not something you plan to reuse across your whole program.
#Where Lambdas Actually Shine: sorted()
The most common place you'll see lambdas in real Python code is as the key= argument to sorted(), min(), and max(). These functions let you say how to compare items — and a lambda is a perfect fit because the logic is usually just one expression.
names = ["Alice", "Bob", "Charlie", "Di"]
# Sort by the LENGTH of each name, shortest first
sorted_names = sorted(names, key=lambda name: len(name))
print(sorted_names)products = [
{"name": "apple", "price": 0.99},
{"name": "banana", "price": 0.49},
{"name": "cherry", "price": 3.99},
]
# Find the cheapest product
cheapest = min(products, key=lambda p: p["price"])
print(cheapest["name"])#Lambdas with map() and filter()
map() applies a function to every item in a list. filter() keeps only the items for which a function returns True. Both accept a function as their first argument — lambdas fit naturally here.
numbers = [1, 2, 3, 4, 5]
# Square every number
squared = list(map(lambda n: n ** 2, numbers))
print(squared)
# Keep only even numbers
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)List comprehensions are often cleaner
Many experienced Python developers prefer list comprehensions over map/filter with lambdas because they read more like plain English:
``python squared = [n ** 2 for n in numbers] evens = [n for n in numbers if n % 2 == 0] ``
Both approaches work — pick whichever feels more readable to you and your team.
#Lambdas with Multiple Parameters
A lambda can accept more than one parameter — just separate them with commas, the same way you would in a def.
add = lambda x, y: x + y
print(add(3, 7))#The Key Limit: One Expression Only
A lambda can only contain a single expression — it cannot contain statements like if/else blocks, for loops, print() calls, or return. The moment your logic needs more than one step, reach for a regular def instead.
You can't put statements inside a lambda
This will cause a SyntaxError:
``python # WRONG — statements are not allowed lambda x: if x > 0: return x return -x ``
Instead, write a proper function:
``python def absolute_value(x): if x > 0: return x return -x ``
If the logic doesn't fit on one line comfortably, it doesn't belong in a lambda.
#Assigning a Lambda to a Name — Usually a Smell
You can assign a lambda to a variable, like double = lambda x: x * 2. But Python's own style guide (PEP 8) warns against this. If you're giving the function a name anyway, just use def — it's more readable, easier to debug, and plays nicer with tools.
# Technically works, but discouraged
double = lambda x: x * 2
# Preferred — clearer and just as short
def double(x):
return x * 2Named lambdas are harder to debug
When a named lambda raises an error, the traceback shows <lambda> instead of the function's name — which makes debugging much harder. A def function always shows its actual name in tracebacks, making problems easier to find.
#When to Use Lambda vs. def
Here's a simple rule of thumb:
- Use `lambda` when you need a short, one-expression function inline — especially as a
key=argument or withmap/filter. - Use `def` when the logic has multiple steps, when you'll reuse the function, or when giving it a name makes your intent clearer.
Readability always wins.
Which of the following is a valid use of a lambda function?
Key takeaways
- A lambda is a one-line anonymous function: `lambda params: expression`.
- They shine as `key=` arguments in `sorted()`, `min()`, and `max()`.
- Lambdas only support a single expression — no loops, assignments, or multi-line logic.
- Assigning a lambda to a name is usually a sign you should use `def` instead.
- When in doubt, choose `def` — it's easier to read, test, and debug.
What does this code print?
numbers = [3, 1, 4, 1, 5]
sorted_nums = sorted(numbers, key=lambda n: -n)
print(sorted_nums)This code is supposed to keep only the words longer than 3 characters, but it has a bug. What is wrong?
words = ["hi", "hello", "cat", "world"]
long_words = list(filter(lambda w: return len(w) > 3, words))
print(long_words)Complete the lambda so that sorted() orders the names from shortest to longest.
names = ["Charlie", "Bo", "Alice", "Di"] result = sorted(names, key=lambda name: (name)) print(result)
Put these lines in the right order to square every number in the list and print the result.
squared = list(map(lambda n: n ** 2, numbers))
print(squared)
numbers = [1, 2, 3, 4]
You have a list of student records, each a dictionary with a "name" and a "score". Use sorted() with a lambda to sort the students by score from highest to lowest. Then use filter() with a lambda to create a list of only the students who passed (score >= 60). Print both results.
Try it live — edit the code and hit Run to execute real Python: