Lambda, map, and filter
Write small anonymous functions, transform iterable values with map(), and select matching items with filter().
In this lesson, you will learn
- ✓Explain what lambda expressions do and how they differ from named functions defined with def.
- ✓Write lambda expressions containing parameters and a single expression.
- ✓Use map() to transform every item in an iterable.
- ✓Use filter() to retain items whose predicate results are truthy.
- ✓Explain why map() and filter() return iterators in Python 3 and how list() consumes their results.
- ✓Trace the behavior of lambda, map(), and filter() with ordinary inputs and edge cases.
- ✓Compare functional-style operations with list comprehensions and choose a readable solution.
1. Lambda expressions: small anonymous functions
A function is a reusable block of code that can accept inputs and produce a result. You have already learned to define functions with def. Python also supports lambda expressions, which create small anonymous function objects.
The general syntax is lambda parameters: expression. The parameters are the inputs, and the expression is evaluated to produce the function's return value.
For example, lambda x: x * 2 defines a function that accepts x and calculates twice its value. If you call that function with 5, the result is 10.
A lambda expression contains one expression, not a sequence of statements. It can contain an expression such as a calculation, comparison, conditional expression, or function call. For multi-step logic, a regular function defined with def is usually clearer.
Lambda functions are often passed directly to other functions such as map(), filter(), and sorted(). The function can be used without first assigning it a separate name.
Create and call a lambda function
lambda x: x * 2 creates a function that accepts one parameter, x. The expression x * 2 calculates the returned value. Calling double(5) evaluates 5 * 2 and returns 10. Calling double(8) evaluates 8 * 2 and returns 16. Assigning the lambda to double gives the function a variable name, although the function itself is still created with a lambda expression.
Note
2. Lambda compared with def
A lambda expression and a function defined with def can both create callable functions. The important difference for beginners is how they are written and how much logic they can express clearly.
Use lambda for a short expression when a small function is useful in a larger operation. Use def when the logic needs multiple statements, documentation, a meaningful function name, or more involved error handling.
Both forms can accept parameters and return values. Choosing lambda does not make the calculation inherently faster or more correct; readability should guide the choice.
Equivalent lambda and def functions
Both functions accept a number and return twice its value. The lambda expresses the calculation in one expression. The def version uses a named function body and an explicit return statement. For this simple operation, either form works.
Caution
3. map(): transform every item
The built-in map() function applies a function to items from an iterable. Its basic syntax is map(function, iterable). The function receives each item, and its return value becomes the corresponding mapped result.
Use map() when you want to perform the same transformation on every item, such as doubling numbers, converting strings to integers, or calculating the lengths of words.
In Python 3, map() returns an iterator rather than a list. An iterator produces values as they are requested. To display all mapped values together, a common beginner-friendly approach is list(map(function, iterable)).
The iterable is processed in its iteration order. Mapping does not automatically sort the values or remove duplicates. If the input has repeated values, the mapped results can also contain repeated values.
Double every number
map() takes the lambda function and the numbers list. For each input number, the lambda calculates n * 2. The mapped values are 2, 4, 6, and 8. list() consumes the map iterator and collects the values into a list.
Note
4. Trace map() step by step
To understand map(), identify the input iterable, the function being applied, and the value produced for each input item.
The expression inside lambda is evaluated separately for each item. The result from one item does not automatically replace or change the original input value.
The map iterator produces mapped results when they are requested. In examples that wrap map() in list(), the iterator is consumed and all results are collected immediately.
Add one to each value
For x = 2, the function returns 3. For x = 3, the function returns 4. For x = 4, the function returns 5. list() collects those results into [3, 4, 5].
Note
5. filter(): keep items that pass a test
The built-in filter() function selects items from an iterable according to a function. Its basic syntax is filter(function, iterable). The function is usually called a predicate because its purpose is to test a value.
If the function returns a truthy result for an item, filter() includes that original item. If the result is false, the item is skipped. The predicate does not replace the item with its return value.
In Python 3, filter() returns an iterator. Use list(filter(function, iterable)) when you want to collect and display all matching items immediately.
A predicate often returns True or False, but Python accepts any truthy or falsy return value. For clarity, beginners should usually write predicates whose purpose is obvious, such as lambda n: n > 0.
Keep numbers greater than three
The predicate n > 3 checks each number. The condition is true for 4, 6, and 8. Those original numbers are included in the result. The numbers 1, 3, and 2 are excluded.
Caution
6. Trace filter() step by step
To trace filter(), examine each input item and evaluate the predicate. If the result is truthy, keep the original item; otherwise, skip it.
The predicate may be a lambda or a named function. What matters is that it tests each item and produces a truthy or falsy result.
If no items pass the predicate, converting the filter iterator to a list produces an empty list. That is a valid result, not an error.
Filter numbers greater than one
For 1, the condition 1 > 1 is false, so 1 is skipped. For 2, the condition is true, so the original value 2 is kept. For 3, the condition is true, so the original value 3 is kept. The final list is [2, 3].
Note
7. Combine lambda, map(), and filter()
The three tools can be combined. A common pattern is to filter an iterable first and then transform the selected values with map().
For example, you can select positive numbers and then square them. The filter decides which inputs are accepted, while the map function calculates a new value for every accepted input.
In a nested expression, read the innermost operation first. In list(map(function, filter(predicate, values))), filter selects values from the input, and map transforms the selected values.
Although these expressions can be compact, do not combine them if the result becomes difficult to read. Named functions or intermediate variables can make the steps easier to understand.
Filter positive numbers and square them
filter(lambda n: n > 0, numbers) selects 2, 4, and 5. map(lambda n: n * n, ...) squares each selected number. list() collects the mapped results into a list. The final result is [4, 16, 25].
Note
8. Iterators, empty inputs, and common edge cases
In Python 3, map() and filter() return iterator objects rather than lists. An iterator produces values as they are requested, instead of storing all results in a list immediately.
Calling list() consumes an iterator and collects its remaining values. If you convert the same exhausted iterator to a list again, the second list is empty. If you need to process the values again, create a new iterator or store the results in a list.
An empty input produces no mapped or filtered items. Therefore, list(map(function, [])) and list(filter(predicate, [])) both produce empty lists.
map() can raise an exception if the supplied function fails for an item. For example, int('abc') raises ValueError because 'abc' is not a valid integer literal. filter() can also raise an exception if its predicate fails.
If you pass multiple iterables to map(), the function must accept the corresponding number of arguments. Iteration stops when the shortest input iterable is exhausted.
Map and filter with empty input
The input list contains no items. map() has no values to transform, so the result is empty. filter() has no values to test, so its result is also empty.
Caution
9. Compare map() and filter() with comprehensions
Many transformations and filters can be written with either functional-style tools or comprehensions. Neither approach is automatically best for every situation.
Use map() when applying an existing function to every item makes the intention clear. Use filter() when selecting items with a predicate is the clearest approach. List comprehensions are often especially readable when both transformation and filtering are needed.
A list comprehension creates a list directly. By contrast, map() and filter() return iterators in Python 3, so list() is commonly used when a complete list is required.
Choose the version that makes the operation easiest to understand. Avoid adding lambda, map(), and filter() simply to make a short task appear more advanced.
Equivalent map() and list comprehension
Both versions double every number. map() applies the lambda to every input item. The list comprehension evaluates n * 2 for each input item. Both produce the same list, and the comprehension may be easier to read for this simple transformation.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Writing multiple statements or a return statement inside a lambda expression.
Why it happens: A lambda expression contains one expression whose value is returned implicitly; multi-step logic belongs in a def function.
Key takeaway: A lambda body contains one expression, whose value is returned automatically. Use def for multi-statement logic.
#2 Assuming map() returns a list in Python 3.
Why it happens: In Python 3, map() returns a lazy iterator, so use list(map(...)) when a materialized list is required.
Key takeaway: map() returns an iterator. Wrap it in list() when you need a list of all results.
#3 Assuming filter() returns the Boolean results of its predicate.
Why it happens: filter() yields the original items whose predicate is truthy; it does not yield the predicate's Boolean results.
Key takeaway: filter() returns the original input items whose predicate results are truthy. It does not return the predicate results themselves.
#4 Using map() when items should be excluded rather than transformed.
Why it happens: map() transforms each input item, while filtering removes items that do not satisfy a condition.
Key takeaway: Use filter() to select items based on a predicate, or use a list comprehension with an if clause.
#5 Using filter() when each item needs a new calculated value.
Why it happens: filter() selects existing items; use map() or a comprehension when each item must be transformed into a new value.
Key takeaway: Use map() to transform each item or use a list comprehension with a transformation expression.
#6 Forgetting to convert an iterator to a list when the task requires a displayed collection.
Why it happens: Lazy iterators do not display as a complete collection automatically; materialize them only when the task requires it.
Key takeaway: Use list(map(...)) or list(filter(...)) to collect the results for display.
#7 Expecting a consumed iterator to produce the same values again.
Why it happens: An iterator advances as it is consumed, so a second pass may yield nothing unless a fresh iterator is created.
Key takeaway: Iterators are consumed as values are requested. Create a new iterator or store the values in a list if you need to reuse them.
#8 Assuming that lambda, map(), and filter() are always clearer than comprehensions.
Why it happens: Comprehensions often express simple transformations and filters more directly; map() and filter() are not automatically clearer in every situation.
Key takeaway: Choose the simplest readable form. A list comprehension is often clearer for a straightforward transformation combined with filtering.
#9 Passing a function with the wrong number of parameters to map().
Why it happens: map() supplies values from its input iterables to the function, so the callable's parameters must match the number of iterables supplied.
Key takeaway: When map() receives multiple iterables, its function must accept the corresponding number of arguments.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a lambda function in Python?
Q2:What is the difference between lambda and def?
Q3:What does map() do?
Q4:What does filter() do?
Q5:What is the difference between map() and filter()?
Q6:Why do we wrap map() and filter() in list()?
Q7:Can map() accept more than one iterable?
Q8:When would you use a list comprehension instead of map() and filter()?
Key takeaways
- lambda creates a small anonymous function using the syntax lambda parameters: expression.
- A lambda expression contains one expression and returns its value automatically.
- map() applies a function to every item from an iterable and returns an iterator in Python 3.
- filter() retains original items whose predicate results are truthy and returns an iterator in Python 3.
- Use list() when you need to consume and collect all iterator results into a list.
- Use map() to transform values and filter() to select values.
- You can combine filter() and map() to select items before transforming them.
- Iterators are consumed as their values are requested; an exhausted iterator does not automatically restart.
- Named functions defined with def are often clearer for multi-step or reusable logic.
- List comprehensions are often a readable alternative when filtering and transforming a list together.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: