Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 39 of 70

Python lambda functions: small anonymous functions

Learn what a Python lambda is, how it differs from def, and where it helps, such as the key argument for sorting, with real output for each example.

11 minFunctionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite a lambda expression, use it as a sort key or a small callback, and decide when a normal def is the better choice.

After this lesson you can write a one-line function with lambda, use it to sort data by a chosen field, and recognise when a lambda has become too clever.

What a lambda is

A lambda is a function without a name, written on a single line. The shape is the word lambda, the parameters, a colon, and one expression. The value of that expression is what the function returns.

Here is an ordinary function and its lambda twin:

python
def double(x):
    return x * 2

double_lambda = lambda x: x * 2

print(double(4))
print(double_lambda(4))
print(type(double_lambda))
result
8
8
<class 'function'>

They behave the same way. Python style guides prefer def when a function gets a name like this, because a def shows the name in error messages and can hold a docstring. The real value of lambda is when you need a tiny function once, in the middle of another call, and a full def would be noise.

Calling it immediately

Because a lambda is an expression, you can create and call it in one go. This is rarely useful in real code but it shows what a lambda is:

python
print((lambda a, b: a + b)(3, 4))
result
7

Lambdas can have no parameters, several parameters, or default values:

python
greet = lambda name="friend": "Hello, " + name
print(greet())
print(greet("Asha"))
result
Hello, friend
Hello, Asha

The best use: the key argument

Functions such as sorted, min and max accept a key function that says what to compare. Say a shop keeps products as pairs of name and price:

python
products = [("tea", 120), ("coffee", 250), ("milk", 60)]

print(sorted(products))
print(sorted(products, key=lambda item: item[1]))
print(min(products, key=lambda item: item[1]))
print(max(products, key=lambda item: item[1]))
result
[('coffee', 250), ('milk', 60), ('tea', 120)]
[('milk', 60), ('tea', 120), ('coffee', 250)]
('milk', 60)
('coffee', 250)

The first line sorts by name, since tuples compare element by element. The key version sorts by price, because for each tuple the lambda picks out the second element. The function is used once, so naming it would add nothing.

The same idea works with dictionaries:

python
students = [
    {"name": "Asha", "marks": 82},
    {"name": "Ben", "marks": 91},
    {"name": "Chloe", "marks": 77},
]
best_first = sorted(students, key=lambda s: s["marks"], reverse=True)
print([s["name"] for s in best_first])
result
['Ben', 'Asha', 'Chloe']

Conditional expressions

A lambda cannot contain statements such as a full if block, but it can use the one-line conditional expression, which is itself an expression:

python
grade = lambda marks: "pass" if marks >= 40 else "fail"
print(grade(55))
print(grade(30))
result
pass
fail

Lambdas as callbacks

You can also keep lambdas in a data structure, which gives a simple way to choose behaviour by name:

python
operations = {
    "add": lambda a, b: a + b,
    "multiply": lambda a, b: a * b,
}
print(operations["add"](6, 7))
print(operations["multiply"](6, 7))
result
13
42

When not to use lambda

If you need more than one expression, a loop, an assignment or an error handler, write a def. If the lambda needs a comment to explain it, use def with a good name. Compare:

python
prices = [100, 250, 80]
with_tax = list(map(lambda p: round(p * 1.18, 2), prices))
print(with_tax)
result
[118.0, 295.0, 94.4]

This is fine because it is short. When it gets longer than about one readable line, give it a name instead.

Lambdas and default values in loops

Lambdas look at variables when they are called, not when they are created. This surprises people who build several lambdas in a loop:

python
multipliers = [lambda x: x * n for n in [1, 2, 3]]
print([f(10) for f in multipliers])

fixed = [lambda x, n=n: x * n for n in [1, 2, 3]]
print([f(10) for f in fixed])
result
[30, 30, 30]
[10, 20, 30]

In the first list every lambda uses the final value of n, which is 3, so all three give 30. The second version stores the current n as a default value, giving the intended 10, 20 and 30. You will not need this trick often, but it explains an odd bug when you meet it.

Common mistakes

  • Writing return inside a lambda. The expression is returned automatically, and return is a syntax error there.
  • Putting parentheses round the parameters. Write lambda a, b: a + b, not lambda (a, b): a + b.
  • Trying to put statements in it. Assignments and multi-line logic are not allowed.
  • Squeezing complex logic into one line. Readability beats cleverness every time.
  • Forgetting it is still a function. Without parentheses and arguments you get the function object, not a result.

Here is the first mistake in action:

python
bad = lambda a, b: return a + b
result
SyntaxError: invalid syntax

Exercise

You have the list words = ["banana", "fig", "cherry", "kiwi"]. Use sorted with a lambda key to sort the words by length, shortest first. Then sort them by their last letter.

Show one possible answer
python
words = ["banana", "fig", "cherry", "kiwi"]
print(sorted(words, key=lambda w: len(w)))
print(sorted(words, key=lambda w: w[-1]))
result
['fig', 'kiwi', 'banana', 'cherry']
['banana', 'fig', 'kiwi', 'cherry']

Key points

  • A lambda is a small function written as one expression: lambda arguments: expression.
  • It returns the value of its expression automatically. There is no return keyword.
  • Lambdas are mostly used inline, for example as the key for sorted, min and max.
  • A lambda cannot hold several statements. Use def for anything longer than a single simple expression.
  • Assigning a lambda to a name is legal but def is the clearer style.

Check yourself

1. What does (lambda x: x * 2)(5) give?
2. Which is a valid lambda that adds two numbers?
3. What is a good use of a lambda?
4. Can a lambda contain an if statement block with several lines?