Intermediate Chapter 83 · 25 min read · Module 6: Python Functions
Lambda Functions
- After this chapter you can write a lambda expression.
- You can use lambda as a key for sorted, min and max.
- You can combine lambda with map and filter.
- You can decide when a normal def function is better.
- You can avoid the late-binding trap in lambdas created in loops.
Sometimes you need a tiny function just once, for example to say how a list should be sorted. Writing a full def block for that feels heavy. Python offers the lambda expression for these small jobs.
A lambda is a function without a name. It has parameters and one expression, and it returns the value of that expression. You can store it in a variable, pass it to another function, or call it right away.
In this chapter you will learn the syntax, see the most common uses, and learn the limits. Lambdas are a tool for short code, not for hiding complex logic.
The lambda syntax
A lambda starts with the word lambda, then the parameters, a colon, and one expression. There is no return keyword. The result of the expression is returned automatically.
lambda parameters: expression.def square(x):
return x * x
square2 = lambda x: x * x
print(square(5))
print(square2(5))
print((lambda a, b: a + b)(3, 4))Both square and square2 do the same job. The last line creates a lambda and calls it at once. Lambdas can take several parameters, default values and even *args, just like normal functions.
square2 = lambda .... If a function needs a name, use def. It gives better error messages and allows a docstring.Lambda as a sort key
The most popular use is the key argument of sorted, list.sort, min and max. The key function receives each item and returns the value to compare.
words = ['pear', 'fig', 'banana', 'kiwi']
print(sorted(words, key=lambda w: len(w)))
students = [('Asha', 82), ('Ravi', 91), ('Mina', 75)]
print(sorted(students, key=lambda s: s[1], reverse=True))
print(max(students, key=lambda s: s[1]))The first sort orders words by length. Because sorted is stable, pear stays before kiwi, since both have four letters and pear came first. The second sort orders pairs by their score, highest first.
Lambda with map and filter
map(function, items) applies a function to every item. filter(function, items) keeps the items for which the function returns a true value. Both return lazy iterators, so wrap them in list() to see the values.
nums = [1, 2, 3, 4, 5, 6]
squares = list(map(lambda n: n * n, nums))
evens = list(filter(lambda n: n % 2 == 0, nums))
print(squares)
print(evens)Many Python programmers prefer list comprehensions for this work, such as [n * n for n in nums]. Both styles are correct. Choose the one that reads more clearly.
Conditional expressions inside lambda
A lambda body must be a single expression, so you cannot use if statements or loops. But you can use the conditional expression a if condition else b.
grade = lambda marks: 'pass' if marks >= 40 else 'fail'
print(grade(72))
print(grade(35))
print([grade(m) for m in (40, 39)])Lambdas stored in data structures
Because functions are values, you can keep lambdas in a dictionary and pick one by name. This is a neat replacement for a long chain of if and elif lines.
ops = {
'add': lambda a, b: a + b,
'sub': lambda a, b: a - b,
'mul': lambda a, b: a * b,
}
for name in ('add', 'sub', 'mul'):
print(name, ops[name](6, 3))Late binding in loops
A lambda looks up variables from the surrounding scope when it is called, not when it is created. If you make lambdas in a loop, they all see the final value of the loop variable. The fix is to give the variable as a default argument, which is evaluated at creation time.
bad = [lambda: i for i in range(3)]
good = [lambda i=i: i for i in range(3)]
print([f() for f in bad])
print([f() for f in good])Why the name lambda?
The word comes from lambda calculus, a branch of mathematics where functions have no names. You do not need any math to use it. Just remember that a lambda is a nameless helper that you write exactly where you need it. Because it has no name, error messages show <lambda> instead of a useful label, which is one more reason to keep lambdas short.
A good test is to read the lambda aloud. lambda w: len(w) reads as: given w, give back the length of w. If you cannot read it in one breath, it is too long. Another useful habit is to look for a ready-made tool first. For example, key=len does the same as key=lambda w: len(w), and it is shorter and clearer.
Lambdas also work well as small callbacks. A callback is a function that you hand to other code so that it can call you back later. Buttons in a window, timers, and sorting routines all accept callbacks. A lambda lets you write that tiny piece of behaviour right at the place where it is used, so the reader does not have to jump to another part of the file.
When not to use lambda
- When the logic needs more than one expression, statements, or comments.
- When the same function is used in many places. Give it a name with def.
- When a built-in does the job, such as
operator.itemgetter(1)orstr.lower. - When the lambda becomes hard to read. Clear code is better than short code.
Python syntax
lambda parameters: expressionlambda x, y=2: x ** ysorted(items, key=lambda item: item[1])lambda n: 'even' if n % 2 == 0 else 'odd'Real-world applications
- Sorting records by a field such as price or date.
- Finding the largest item by a custom rule with max.
- Quick transformations with map and filter.
- Callbacks in GUI toolkits and small dispatch tables.
Common mistakes
Fix: A lambda can hold only one expression. Use def for anything longer.
Fix: Use list(map(...)) to see the values, otherwise you print an iterator object.
Fix: Use a default argument like lambda i=i: i.
Fix: Switch to a named def function with a docstring.
Important tips
- Use lambda for keys and short callbacks only.
- If you need to name it, use def.
- Try a list comprehension before map and filter.
- Test a lambda by calling it with sample values in the shell.
Key points summary
- lambda creates a function from one expression.
- The expression value is returned automatically.
- Lambdas are common as key functions.
- They cannot contain statements.
- Variables are looked up when the lambda is called.
Exam and interview points
- Syntax: lambda args: expression.
- A lambda returns its expression value without return.
- Common with sorted, min, max, map and filter.
- Late binding happens for variables from outer scopes.
Quick revision
- lambda x: x + 1 is a function.
- Only one expression allowed.
- key=lambda ... is the top use.
- map and filter return iterators.
- Use def when it grows.
Frequently asked questions
Is a lambda different from a normal function?
Not in behaviour. It is a function object like any other, but it has no name and its body is only one expression.
Can a lambda have no parameters?
Yes. Write lambda: 42 and call it with f().
Can I use if inside a lambda?
Only the conditional expression form, a if condition else b. The if statement is not allowed.
Are lambdas faster than def functions?
No. They run at the same speed. Choose by readability, not speed.
Practise this chapter
20 practice questions Take the chapter quiz