Lambda Functions
Learn how to write small anonymous functions in Python using lambda, and when to use them instead of a full function.
Introduction
Sometimes you need a very small function just for a single, throwaway purpose — like telling sorted() what to sort by. Writing a full def block for something so small can feel like overkill. Python's answer to this is the lambda: a way to write a small, unnamed function in a single line.
This lesson covers lambda syntax, when a lambda is the right tool (and when it is not), and how lambdas are commonly used with sorted(), max(), min(), filter(), and map().
- The syntax for writing an anonymous lambda function.
- When to reach for a lambda instead of a full def function.
- How to use a lambda as a key function for sorted(), max(), and min().
- How to use lambda with filter() and map().
- The limitations of lambda functions.
Lambda Syntax
A lambda function is written as the keyword lambda, followed by any parameters, a colon, and a single expression whose result is automatically returned. It has no name unless you assign it to a variable.
square = lambda x: x * x
print(square(5))
print(square(9))25
81lambda x: x * x is an anonymous function equivalent to def square(x): return x * x. Assigning it to the name square lets you call it just like a normal function.
add = lambda a, b: a + b
print(add(4, 7))11lambda Keyword
Signals that you are creating an anonymous function.
Parameters
Zero or more parameters, separated by commas, just like a normal function.
Single Expression
Exactly one expression after the colon — its value is returned automatically.
No Name Required
A lambda does not need to be assigned to a variable to be used.
Lambda vs. a Full Function
A lambda is best suited for short, throwaway logic that is used once or passed directly into another function. A regular def function is better whenever the logic is reused, needs a name for clarity, spans multiple steps, or needs a docstring.
Use a lambda when...
- The logic is a single simple expression.
- You need a quick function just for one call, like a sort key.
- Naming the function would not add any real clarity.
Use def when...
- The logic requires multiple steps or statements.
- You will reuse the function in several places.
- A clear name or a docstring would help readability.
# As a full function
def square(x):
return x * x
# As a lambda
square_lambda = lambda x: x * x
print(square(6))
print(square_lambda(6))36
36Both versions behave identically here. The def version is more readable for something meant to be reused and named; the lambda version shines when this logic is only needed briefly, inline, as you will see next.
Lambda as a Sort Key
One of the most common uses of lambda is as the key argument to sorted(), telling Python exactly what value to sort by.
students = [("Maya", 88), ("Sam", 95), ("Alex", 72)]
sorted_by_score = sorted(students, key=lambda student: student[1])
print(sorted_by_score)[('Alex', 72), ('Maya', 88), ('Sam', 95)]For each tuple in students, sorted() calls the lambda to get student[1] — the score — and sorts based on that value instead of the whole tuple.
sorted_desc = sorted(students, key=lambda student: student[1], reverse=True)
print(sorted_desc)[('Sam', 95), ('Maya', 88), ('Alex', 72)]Lambda with max() and min()
max() and min() also accept a key function, letting you find the largest or smallest item according to a custom rule instead of Python's default comparison.
students = [("Maya", 88), ("Sam", 95), ("Alex", 72)]
top_student = max(students, key=lambda student: student[1])
lowest_student = min(students, key=lambda student: student[1])
print("Top student:", top_student)
print("Lowest student:", lowest_student)Top student: ('Sam', 95)
Lowest student: ('Alex', 72)Without the key argument, max() and min() would try to compare whole tuples starting from the name, which is not what we want here — the lambda tells them to compare by score instead.
Lambda with filter()
filter() builds a new sequence containing only the items for which a function returns True. A lambda is a natural fit here since the filtering condition is usually a single short expression.
numbers = [4, 9, 15, 22, 7, 30, 3]
even_numbers = list(filter(lambda n: n % 2 == 0, numbers))
print(even_numbers)[4, 22, 30]filter() calls the lambda once per item in numbers, keeping only the values where n % 2 == 0 evaluates to True. Wrapping the result in list() converts the filter object into a visible list.
Lambda with map()
map() applies a function to every item in a sequence and returns the transformed results. Combined with a lambda, this is a compact way to transform data without writing a full loop.
prices = [100, 250, 75, 400]
discounted = list(map(lambda price: price * 0.9, prices))
print(discounted)[90.0, 225.0, 67.5, 360.0]map() runs the lambda on every price in the list, producing a new list where each value has been multiplied by 0.9 — a 10% discount applied to every item at once.
- [price * 0.9 for price in prices] achieves the exact same result as the map()+lambda version.
- Many Python developers prefer list comprehensions for readability over map()/filter() with lambda.
- Both approaches are valid — comprehensions are covered in a dedicated lesson later in this course.
Limitations of Lambdas
Lambdas are intentionally restricted to keep them simple. A lambda body must be a single expression — it cannot contain statements like if/else blocks (other than a conditional expression), loops, multiple lines, or assignments.
No Statements
A lambda cannot contain for loops, while loops, or assignment statements.
One Expression Only
The entire body must be a single expression whose value is returned.
No Docstrings
Lambdas cannot have a docstring documenting what they do.
Harder to Debug
Anonymous functions produce less helpful names in tracebacks and error messages.
label = lambda score: "Pass" if score >= 40 else "Fail"
print(label(72))
print(label(30))Pass
FailThis works because if/else used this way is a conditional expression (a single expression that evaluates to a value), not a multi-line if statement — lambdas can use expressions like this, just not full statements.
Common Mistakes
- Trying to fit multi-step logic into a lambda instead of just writing a def function.
- Forgetting that filter() and map() return special objects that must be wrapped in list() to view.
- Overusing lambdas for complex conditions, which hurts readability instead of helping it.
- Assigning a lambda to a variable and then wondering why it has no helpful name in error tracebacks.
- Trying to use a print statement or assignment inside a lambda body — only expressions are allowed.
Best Practices
- Use lambda for short, one-off logic — especially as a key function for sorted(), max(), or min().
- Prefer a named def function whenever the logic will be reused or needs a docstring.
- Keep lambda expressions simple and easy to read at a glance.
- Consider a list comprehension as a often more readable alternative to map()/filter() with lambda.
- Avoid nesting multiple lambdas inside each other — it quickly becomes hard to read.
Frequently Asked Questions
Is a lambda function faster than a regular function?
No, lambda functions run at essentially the same speed as an equivalent def function. The benefit of lambda is conciseness for short, throwaway logic, not performance.
Can a lambda have multiple lines?
No. A lambda body must be exactly one expression. If you need multiple steps or statements, use a regular def function instead.
Can I use if/else inside a lambda?
Yes, but only as a conditional expression, like lambda x: "even" if x % 2 == 0 else "odd", not as a multi-line if statement.
Why does filter() or map() return something that looks empty when printed?
filter() and map() return lazy iterator objects, not lists. Wrap the result in list() to see and use the actual values, like list(filter(...)).
Should I always use lambda with sorted(), filter(), and map()?
Not always. For short logic, lambda is convenient. For anything more complex, defining a named function (or using a list comprehension) is usually more readable.
Key Takeaways
- A lambda is a small, anonymous function limited to a single expression.
- Lambdas are ideal for short, throwaway logic rather than reusable, multi-step functions.
- A lambda is commonly used as the key argument for sorted(), max(), and min().
- filter() uses a lambda to keep only items for which it returns True.
- map() uses a lambda to transform every item in a sequence.
- Lambdas cannot contain statements — only a single expression is allowed.
Summary
Lambda functions give you a compact way to write small, anonymous functions for one-off tasks, especially alongside sorted(), max(), min(), filter(), and map(). They trade flexibility for brevity, so they work best for simple, single-expression logic.
When logic grows beyond a single expression, or needs to be reused and documented, a regular def function is still the better choice. Next, you will explore recursion — functions that call themselves to solve a problem.
- You can write anonymous functions using lambda syntax.
- You know when a lambda is preferable to a full function, and when it is not.
- You can use lambda with sorted(), max(), and min() as a key function.
- You can use lambda with filter() and map() to process sequences.
- You understand the limitations of lambda functions.
- You are ready to learn about recursion.