Python lambda functions explained, with sorted() key examples
A Python lambda is a small function written as one expression. See the syntax, how it powers sorted(), max() and min(), and when def is clearer.

What is a Python lambda, and why does it keep showing up inside sorted()?
Short answer: a lambda is a small, unnamed function written as a single expression. You'll use it most as the key= for sorted(), max() and min(), where you need a tiny function once and there's no point giving it a name.
By the end of this post you will read lambda syntax at a glance, sort a list of scores by any field, break ties, and know when a regular def is the better choice. If functions are still new, start with Defining Functions (opens in a new tab) and Return Values (opens in a new tab).
Lambda syntax in one line
Here's the same function written both ways:
def add(a, b):
return a + b
print(add(2, 3)) # 5
print((lambda a, b: a + b)(2, 3)) # 5A lambda has three parts:
- The keyword
lambda. - Its parameters, separated by commas, just like in
def. Defaults and*argswork too. - A colon, then one expression. Python returns that expression's value automatically, so there's no
returnkeyword.
That last rule is the whole limit. A lambda can't hold statements: no return, no assignment with =, no loops, no if blocks. A conditional expression is fine, because it's still one expression: lambda n: "even" if n % 2 == 0 else "odd".
Where lambdas earn their place: sorting with key=
sorted(), max() and min() all take a key= argument. You give it a function, Python calls that function on each item, and it compares the results instead of the items themselves. A lambda is the shortest way to write that function on the spot.
scores = [("Ana", 82), ("Bo", 95), ("Cy", 82)]
print(sorted(scores, key=lambda player: player[1]))
# [('Ana', 82), ('Cy', 82), ('Bo', 95)]
print(max(scores, key=lambda player: player[1]))
# ('Bo', 95)Each tuple is (name, score), so player[1] is the score. Without the key, Python would sort by name first, because it compares tuples item by item.
Add reverse=True for highest first. For a tie-breaker, return a tuple from the lambda. Python compares the first value, then the second if the first ties:
print(sorted(scores, key=lambda player: (-player[1], player[0])))
# [('Bo', 95), ('Ana', 82), ('Cy', 82)]-player[1] puts the highest score first, and player[0] breaks the tie alphabetically. The minus sign trick only works on numbers. To mix directions on text, sort twice, because Python's sort is stable and keeps the earlier order for equal keys.
The same pattern works on a list of dictionaries, which is what most real data looks like:
players = [{"name": "Ana", "score": 82}, {"name": "Bo", "score": 95}]
leaders = sorted(players, key=lambda p: p["score"], reverse=True)Sorting With Key (opens in a new tab) practices exactly this, and Leaderboard (opens in a new tab) turns it into a small project.
You don't always need a lambda
If a function that does the job already exists, pass it directly. No lambda, no parentheses:
words = ["banana", "apple", "Cherry"]
print(sorted(words)) # ['Cherry', 'apple', 'banana']
print(sorted(words, key=str.lower)) # ['apple', 'banana', 'Cherry']
print(sorted(words, key=len)) # ['apple', 'banana', 'Cherry']Plain sorted() puts Cherry first because uppercase letters sort before lowercase ones. key=str.lower compares the lowercase versions instead, which is what people usually expect. For picking an item or field, operator.itemgetter(1) does the same as lambda p: p[1], and some teams prefer it for readability.
lambda with map() and filter()
You'll also see lambdas inside map() and filter():
numbers = [1, 2, 3, 4]
print(list(map(lambda n: n * 2, numbers))) # [2, 4, 6, 8]
print(list(filter(lambda n: n % 2, numbers))) # [1, 3]Both work, but a list comprehension usually reads better in Python: [n * 2 for n in numbers] and [n for n in numbers if n % 2]. Our guide to list comprehensions covers that style.
When to use def instead
Reach for a regular function when:
- It needs more than one expression. If you're squeezing logic into a lambda with nested conditionals, it's already too long.
- You want to reuse it. If you find yourself writing
name = lambda ..., usedef name(...)instead. Python's style guide, PEP 8, recommends exactly that, and errors become easier to read because the function has a real name instead of<lambda>. - It deserves a docstring. A lambda has nowhere to put one.
A good rule: if you'd read the lambda aloud and it takes more than one breath, make it a def.
Common mistakes
- Writing
returninside a lambda.lambda x: return xis aSyntaxError. The expression's value is already returned. - Calling the function you pass as
key.sorted(words, key=len())raisesTypeError: len() takes exactly one argument (0 given). Passkey=len, without parentheses, sosorted()can call it for you. - Expecting
list.sort()to return the list.numbers.sort(key=...)sorts in place and returnsNone. Usesorted()when you need a new list back. - Creating lambdas in a loop.
[lambda: i for i in range(3)]gives three functions that all return2, because each one looks upiwhen it's called, not when it's made. Capture the current value with a default:lambda i=i: i.
Quick recap
- A lambda is
lambda parameters: expression, and the expression's value is returned. - It holds one expression only, with no statements.
- Its best job is a short
key=forsorted(),max()andmin(). - Return a tuple from the key to sort by more than one field.
- If you name it, reuse it, or it grows, write a
def.
Frequently asked questions
What is lambda in Python?
It's a way to create a small function without a name, using the lambda keyword. lambda x: x * 2 is a function that doubles its argument, just like a def with a one-line return.
Can a lambda have multiple arguments?
Yes. lambda a, b: a + b takes two, and defaults like lambda a, b=2: a + b work too. What a lambda can't have is more than one expression.
Is a lambda faster than def?
Not in any way you'd notice. Both create the same kind of function object. Choose based on readability, not speed.
How do I sort a list of dictionaries by a value?
Pass a lambda that picks the value: sorted(players, key=lambda p: p["score"]). Add reverse=True for highest first.
Practice
Try the exercises in your browser, with nothing to install: Lambda (opens in a new tab), then Sorting With Key (opens in a new tab), then the Leaderboard (opens in a new tab) project. For more reps on functions and lists, try the Python Functions and Python Lists challenges.
Where to go next
Lambdas sit in the functions module of Intermediate Python (opens in a new tab), next to Keyword Arguments (opens in a new tab), Args (opens in a new tab) and Kwargs (opens in a new tab). If you're earlier in Python, our 30-day Python roadmap shows where this fits.







