Explain it simply
Explain it simply
When you want a friend to rearrange a bookshelf, you just say "sort them by height". You do not write a named instruction manual for that one request. A lambda is Python's version of that short, one-off instruction.
lambda s: s["age"] says "give me an s and I will hand back its age". Pass that tiny function straight to sorted() and sorted() calls it on every item, then orders the items by the ages it got back. You write the function right where it is used, without giving it a name.
Problem → Why → Solution
The problem: a file full of one-use helper functions
Say you must sort a list of students by age, by score and by name. Dicts cannot be compared with each other directly, so sorted() needs a key function. Writing a separate def for each ordering creates many names for one-line jobs, and readers have to jump around to find each one. Sorting without any key function simply raises a TypeError.
students = [{"name": "Sai", "age": 25}, {"name": "Aye", "age": 20}]
def get_age(s): # used exactly once
return s["age"]
def get_name(s): # used exactly once
return s["name"]
print(sorted(students, key=get_age))
print(sorted(students)) # TypeError: '<' not supported between dict and dictWhy is a key function needed?
sorted() compares items with <, and < has no meaning between two dicts. key= is a function that turns each item into something comparable, such as a number, a string or a tuple. When that function is a one-liner, writing it as a lambda at the call site is clearer than defining it elsewhere.
Core concept: a function made of one expression
A lambda is written lambda parameters: expression. It creates a function object that, when called, evaluates the expression and returns the result automatically, with no return keyword. lambda x, y: x + y behaves just like def add(x, y): return x + y. Parameters can use default values, *args and **kwargs exactly as in a def.
The limit is that the body must be a single expression. Statements such as if/else blocks, for loops, assignments with =, try/except and return cannot appear. A conditional expression, a if cond else b, is an expression, so it is allowed. The result is an ordinary function object; apart from its name being "<lambda>", it is no different from a function made with def. That name is also what shows up in tracebacks, which makes it harder to tell which lambda failed.
The most common place for a lambda is a key function. sorted(items, key=f), list.sort(key=f), min(items, key=f) and max(items, key=f) call f once per item and compare the values it returns, while the items themselves stay unchanged. If the key returns a tuple, Python compares the first elements and only looks at the second when they tie, so you can sort by several fields. To sort a number field from high to low, just negate it: -s["score"].
map(f, items) transforms each item with f, and filter(f, items) keeps only the items for which f returns True. Both return lazy iterators, so wrap them in list(). In Python the same jobs can be written as comprehensions, and once a lambda is involved, the comprehension is often easier to read. When a suitable function already exists, such as len or str.lower, pass it directly as key=len instead of wrapping it in a lambda.
- sorted() takes one item
- The key lambda returns a sort value
- Only those values are compared
- Original items come back in order
The key function never changes the items; it only says what to compare.
General pattern
lambda param1, param2: expression # returns expression
sorted(items, key=lambda item: item.field)
sorted(items, key=lambda item: (-item.a, item.b)) # a desc, then b asc
min(items, key=lambda item: item.field)
list(map(lambda item: new_value, items))
list(filter(lambda item: condition, items))The first line is the shape of a lambda. The rest are the places it is most often passed as an argument: key functions, map() and filter().
Example: sorting, transforming and filtering student records
This example applies lambdas in several ways to one list of three dicts. Notice that Sai and Mya share a score of 88; the tuple key breaks that tie by name. Sections 7 and 8 pass an existing function as the key, with no lambda at all.
students = [
{"name": "Sai", "age": 25, "score": 88},
{"name": "Aye", "age": 20, "score": 95},
{"name": "Mya", "age": 30, "score": 88},
]
# 1. A lambda as a sort key: one expression, returned automatically
by_age = sorted(students, key=lambda s: s["age"])
print("1. by age:", [s["name"] for s in by_age])
# 2. Return a tuple to sort by several fields (score high-to-low, then name)
ranked = sorted(students, key=lambda s: (-s["score"], s["name"]))
print("2. ranked:", [s["name"] for s in ranked])
# 3. min() and max() accept the same key argument
print("3. youngest:", min(students, key=lambda s: s["age"])["name"])
# 4. map() applies a function to every item
print("4. map:", list(map(lambda s: s["name"].upper(), students)))
# 5. filter() keeps the items where the function returns True
print("5. filter:", [s["name"] for s in filter(lambda s: s["score"] > 90, students)])
# 6. The same filter as a comprehension, often easier to read
print("6. comprehension:", [s["name"] for s in students if s["score"] > 90])
# 7. An existing function can be the key, no lambda needed
words = ["kiwi", "Banana", "apple"]
print("7. by length:", sorted(words, key=len))
print("8. ignoring case:", sorted(words, key=str.lower))
# 9. A lambda is a normal function object whose name is <lambda>
double = lambda x: x * 2
print("9. name:", double.__name__, double(21))Code breakdown
- Line 8
by_age = sorted(students, key=lambda s: s["age"])sorted() passes each dict to the lambda as s and gets back the ages 25, 20 and 30. Ordering by those numbers gives Aye, Sai, Mya. The original students list keeps its order.
- Line 12
ranked = sorted(students, key=lambda s: (-s["score"], s["name"]))The keys are tuples such as (-95, "Aye"), (-88, "Mya") and (-88, "Sai"). Negating the score puts the highest first, and the two tied at -88 are ordered A-Z by the second element, the name.
- Line 15-16
min(students, key=lambda s: s["age"])["name"]min() returns the whole dict with the smallest age, not the age number itself. That is why ["name"] is applied afterwards to pull out the name.
- Line 19-25
filter(lambda s: s["score"] > 90, students)map() and filter() return iterators, so they are consumed by list() or a comprehension. Section 6 produces the same result as section 5 but reads more plainly, with no lambda or filter() call.
- Line 29-30
sorted(words, key=str.lower)len and str.lower already take one argument, so there is no need for wrappers like lambda w: len(w). With the str.lower key, the capital B sorts after a; without it, capitals would come first.
- Line 33-34
double = lambda x: x * 2A lambda can be stored in a variable, but its __name__ stays "<lambda>". PEP 8 recommends def double(x): whenever you want a named function; this line exists only to show the difference.
1. by age: ['Aye', 'Sai', 'Mya']
2. ranked: ['Aye', 'Mya', 'Sai']
3. youngest: Aye
4. map: ['SAI', 'AYE', 'MYA']
5. filter: ['Aye']
6. comprehension: ['Aye']
7. by length: ['kiwi', 'apple', 'Banana']
8. ignoring case: ['apple', 'Banana', 'kiwi']
9. name: <lambda> 42Lambda or def: which one to choose
| Situation | Better choice |
|---|---|
| Pull out one field for sorted/min/max | lambda (or an existing function) |
| Logic called from several places | def, with a name and docstring |
| Needs if/elif, a loop or try | def (impossible in a lambda) |
| Build a new transformed or filtered list | List comprehension |
A simple rule: if a lambda is not obvious at a glance, turn it into a def. Chained conditional expressions such as a if x else b if y else c, or a lambda nested inside a lambda, are the usual warning signs. Lambdas are also harder to test, because without a name a test cannot call them directly.
In real projects
Where this shows up in real projects
Ordering data the way users will see it is the most common job for a lambda: a leaderboard by score, an order history by date, search results by relevance and then price. JSON from an API usually arrives as a list of dicts, so lines like key=lambda r: r["created_at"] appear in almost every codebase. A call such as max(products, key=lambda p: p["rating"]) finds the best item without writing a loop.
In pandas you meet lambdas in column transformations like df["price"].apply(lambda p: round(p * 1.05, 2)) and in sorts such as df.sort_values(key=lambda col: col.str.lower()). GUI libraries such as Tkinter use them to wrap a button callback with an argument: command=lambda: save("draft"). In code review, though, a lambda stored under a name or stretched across a long line is usually sent back to be rewritten as a def.
Common mistakes
Common mistakes
1. Writing return or a statement inside a lambda
lambda x: return x * 2 is a SyntaxError, because a lambda already returns its expression's value. Assignments like lambda x: total += x and statements like lambda x: if x: ... are SyntaxErrors too. When the logic does not fit in one expression, use a def.
2. Calling the function instead of passing it
Writing sorted(words, key=len()) or key=str.lower() with parentheses calls the function immediately and passes its result as the key, which raises a TypeError. key needs the function object itself: key=len or key=lambda w: len(w).
3. Treating the result of map() or filter() as a list
After evens = filter(lambda n: n % 2 == 0, nums), print(evens) shows only <filter object at ...> and evens[0] raises a TypeError. It is an iterator, so it can be consumed once. Wrap it in list() when you need to reuse the result.
4. Naming a lambda instead of writing a def
calc_tax = lambda price: price * 0.05 works, but tracebacks and logs show only <lambda> and it cannot carry a docstring. Linters warn about it too, for example flake8's E731. If it needs a name, write def calc_tax(price):.
Mini challenge
Mini challenge: a shop's product list
Filter, sort and transform a list of (name, price, in_stock) tuples using lambdas. Do not write loops yourself; use only filter(), sorted(), min() and map().
- Keep only in-stock products with filter()
- Sort by price from high to low, breaking ties by name A-Z
- Find the cheapest product with min()
- Use map() to produce prices with 5% tax, rounded to 2 decimals
products = [
("keyboard", 45.0, True),
("mouse", 19.5, True),
("monitor", 189.0, False),
("cable", 4.0, True),
("webcam", 45.0, True),
]
in_stock = ... # TODO: filter() with a lambda on the third field
# TODO: print the names of the in-stock products
by_price = ... # TODO: sorted() with a tuple key: price descending, name ascending
cheapest = ... # TODO: min() with a key on the price
with_tax = ... # TODO: list(map(...)) adding 5% tax, rounded to 2 decimals
# TODO: print the (name, price) pairs, the cheapest name and the taxed pricesExpected: in stock: ['keyboard', 'mouse', 'cable', 'webcam'] price high to low: [('keyboard', 45.0), ('webcam', 45.0), ('mouse', 19.5), ('cable', 4.0)] cheapest: cable with 5% tax: [47.25, 20.48, 4.2, 47.25]
Show hint
Read tuple fields with p[0], p[1] and p[2]. To sort price high-to-low but names A-Z, negate only the price: key=lambda p: (-p[1], p[0]).
Show solution
products = [
("keyboard", 45.0, True),
("mouse", 19.5, True),
("monitor", 189.0, False),
("cable", 4.0, True),
("webcam", 45.0, True),
]
in_stock = list(filter(lambda p: p[2], products))
print("in stock:", [p[0] for p in in_stock])
by_price = sorted(in_stock, key=lambda p: (-p[1], p[0]))
print("price high to low:", [(p[0], p[1]) for p in by_price])
cheapest = min(in_stock, key=lambda p: p[1])
print("cheapest:", cheapest[0])
with_tax = list(map(lambda p: round(p[1] * 1.05, 2), in_stock))
print("with 5% tax:", with_tax)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- lambda params: expression is an anonymous function that returns its expression's value; it cannot contain statements.
- The key= of sorted(), min() and max() turns each item into a comparable value, and a tuple key sorts by several fields.
- map() and filter() return iterators that need list(), and a comprehension is often clearer.
- Pass existing functions such as len or str.lower directly, and switch to def when it needs a name or grows complex.
Python Documentation — Functional Programming HOWTO — Python Software Foundation