By WebNest Studio Engineering Team
Python Tutorial
Lambda Functions in Python
A lambda is a small anonymous function written in a single expression: lambda x: x * 2. Lambdas are most useful as short "key" or callback functions passed to other functions — sorting by a field, filtering, mapping — where defining a full named function would be overkill.
This lesson covers lambda syntax, using lambdas with sorted, min/max, map and filter, lambdas in dictionaries as simple dispatch tables, the late-binding pitfall, and when to prefer a regular def.
Why it matters
Sorting records by one of their fields, finding the cheapest item, or choosing the longest word all need a small function that says what to compare. A lambda writes that function at the place it is used. You will see lambdas mostly as the key argument of sorted, min and max.
Syntax
lambda parameters: expression creates a function object that returns the expression's value. It can take any number of parameters (including defaults and *args) but must be a single expression — no statements, no assignments (except the walrus operator), no multiple lines. square = lambda x: x ** 2 works but PEP 8 recommends def when you give the function a name.
Where Lambdas Shine
As arguments to higher-order functions: sorted(people, key=lambda p: p["age"]), max(products, key=lambda p: p.price), filter(lambda n: n % 2, numbers), event handlers in GUI code (command=lambda: save(file)), and small dispatch dictionaries mapping names to operations.
Late Binding in Loops
A lambda created in a loop looks up loop variables when it is called, not when it is created, so all of them see the final value. Capture the current value with a default argument: lambda i=i: i.
Examples
Basic lambdas
add = lambda a, b: a + b
greet = lambda name="friend": f"Hello, {name}!"
is_even = lambda n: n % 2 == 0
print(add(3, 4), greet(), greet("Asha"), is_even(10))
print((lambda x: x ** 3)(4))
7 Hello, friend! Hello, Asha! True
64
Sorting and choosing with key functions
products = [
{"name": "Laptop", "price": 55000, "rating": 4.5},
{"name": "Mouse", "price": 700, "rating": 4.8},
{"name": "Keyboard", "price": 1500, "rating": 4.1},
]
by_price = sorted(products, key=lambda p: p["price"])
print([p["name"] for p in by_price])
print(max(products, key=lambda p: p["rating"])["name"])
print(sorted(["banana", "Apple", "cherry"], key=lambda s: s.lower()))
print(sorted([(1, "b"), (1, "a"), (0, "z")], key=lambda t: (t[0], t[1])))
['Mouse', 'Keyboard', 'Laptop']
Mouse
['Apple', 'banana', 'cherry']
[(0, 'z'), (1, 'a'), (1, 'b')]
map, filter and a dispatch table
numbers = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * n, numbers)))
print(list(filter(lambda n: n % 2 == 0, numbers)))
operations = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b if b else "cannot divide by zero",
}
for op in "+-*/":
print(f"8 {op} 2 =", operations[op](8, 2))
print(operations["/"](1, 0))
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
8 + 2 = 10
8 - 2 = 6
8 * 2 = 16
8 / 2 = 4.0
cannot divide by zero
The late-binding pitfall and its fix
buggy = [lambda: i for i in range(3)]
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in buggy])
print([f() for f in fixed])
[2, 2, 2]
[0, 1, 2]
Common Mistakes
- Assigning lambdas to names instead of using def (PEP 8 recommends def).
- Cramming complex logic into a lambda instead of writing a readable function.
- Late binding in loops: capture loop variables with a default argument.
- Using map/filter with lambdas where a comprehension is clearer.
Exercise
Each product is a (name, price) pair. Print the product names ordered from the most expensive to the cheapest, and then the name of the cheapest product. Use a lambda as the key.
Expected output: ['bag', 'book', 'pen'] then pen
products = [("pen", 12), ("bag", 450), ("book", 150)]
# TODO: sort by price, highest first, and print just the names
# TODO: find the cheapest product and print its name
Show hints
key=lambda product: product[1]tellssortedandminto compare by price.reverse=Truesorts from high to low.
Show solution
products = [("pen", 12), ("bag", 450), ("book", 150)]
by_price = sorted(products, key=lambda product: product[1], reverse=True)
print([name for name, price in by_price])
cheapest = min(products, key=lambda product: product[1])
print(cheapest[0])
Quick quiz
1. What can the body of a lambda contain?
- A. A single expression
- B. Any number of statements
- C. Only a return statement
- D. Only arithmetic
Show answer
A. The value of that expression is returned automatically. Statements such as assignments or loops are not allowed.
2. What does (lambda x, y: x + y)(2, 3) evaluate to?
- A. (2, 3)
- B. 5
- C. A function
- D. It raises an error
Show answer
B. The lambda is defined and immediately called with 2 and 3.
3. What does [f() for f in [lambda: i for i in range(3)]] produce?
- A. [0, 1, 2]
- B. [0, 0, 0]
- C. [2, 2, 2]
- D. It raises an error
Show answer
C. Each lambda looks up i when it is called, and by then the loop has finished with i equal to 2.
Interview questions
What is the difference between a lambda and a function defined with def?
Show answer
A lambda is an anonymous function limited to one expression, whose value it returns. A def function has a name, can contain any statements, and can have a docstring. Both create the same kind of function object. Use a lambda for a short function passed as an argument, and def for anything that deserves a name or more than one line.
What is the late-binding problem with lambdas in a loop, and how is it fixed?
Show answer
A lambda does not store the value of an outer variable when it is created; it looks the variable up when it is called. Lambdas created in a loop therefore all see the loop variable's final value. The fix is to capture the current value as a default argument, as in lambda i=i: i, because defaults are evaluated when the lambda is created.
Key Points to Remember
- lambda args: expression creates a small anonymous function.
- Lambdas are ideal as key functions and short callbacks.
- They are limited to one expression.
- Capture loop variables with default arguments to avoid late binding.
- Prefer def for anything named, reused or non-trivial.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering