Python Lambda, map, and filter Exercises
map and filter are short tools for transforming and selecting values. They are easiest to use when the function is simple and you remember that both return lazy iterators in Python 3.
Use lambda for a one-line rule
A lambda is an expression, not a statement. It is useful when a short function is passed directly to another function. If the rule needs a name or several lines, define a normal function with def.
double = lambda n: n * 2
print(double(4))
print((lambda a, b: a + b)(2, 3))Two small lambdas
map changes every item
map(function, values) applies the function to each value. The result is lazy, so list() is needed to display or index it. The input sequence is left unchanged.
nums = [1, 2, 3]
print(list(map(lambda n: n + 1, nums)))Transform each value
filter keeps matching items
filter(predicate, values) keeps only the values for which the predicate returns True. The predicate should return a boolean. Convert the result to a list before printing it.
nums = [1, 2, 3, 4]
print(list(filter(lambda n: n % 2 == 0, nums)))Keep the even values
Combine map and filter
Read the pipeline from the inside out: filter first, then map the remaining values. Give the intermediate result a name if the line becomes hard to follow.
nums = [1, 2, 3, 4, 5]
even = filter(lambda n: n % 2 == 0, nums)
print(list(map(lambda n: n * n, even)))Filter, then transform
Choose readability
A list comprehension often says the same thing with less punctuation. map and filter are fine when the function already exists, such as str.upper or len. Prefer the version a beginner can read in one pass.
names = ["latte", "tea"]
print(list(map(str.upper, names)))
print([name.upper() for name in names])Two readable options
Your practice checklist
- Use lambda only for a short, obvious rule.
- Wrap map and filter results in list() when inspecting them.
- Read a pipeline from the inside out.
- Prefer a comprehension when it is easier to scan.
Common questions
Why does print(map(...)) show an object?
In Python 3, map returns a lazy iterator. Wrap it in list() to consume the values and display them.
Is map faster than a list comprehension?
It depends on the function and the input. For simple transformations, the difference is usually small; readability should come first.
Can filter return values that are not booleans?
It treats truthy and falsy values as the test, but returning an actual boolean is clearer and less error-prone.
Practice lambda, map, and filter
12 questions on anonymous functions, lazy iterators, filtering, and readable alternatives.
Keep reading: