Lambda, Map and Filter in Python
Learn Python lambda functions plus map and filter: write tiny anonymous functions, transform and filter lists, compare with loops and comprehensions, with worked examples.
Key takeaways
- A lambda is a small, unnamed function written in one line
- map applies a function to every item in a sequence
- filter keeps only the items for which a function returns True
- map and filter return special objects, so wrap them in list() to see the results
Tiny functions for tiny jobs
Sometimes you need a function so small that giving it a full name and a def block feels like overkill. Python offers a shortcut called a lambda: a one-line, unnamed function. Paired with map and filter, lambdas let you transform and filter whole lists compactly.
This lesson builds on functions that return values and Python list comprehensions. If comprehensions are new to you, that lesson is a great companion, because lambdas, map and filter solve similar problems in a different style.
What is a lambda?
A normal function:
def square(x):
return x * x
print(square(5)) # 25
The lambda version of the exact same thing:
square = lambda x: x * x
print(square(5)) # 25
Reading lambda x: x * x:
lambdais the keyword that starts an anonymous function.xis the parameter (you can have more, separated by commas).- The part after the colon is the single expression that is automatically returned.
There is no return keyword and no function name (until we assign it). A lambda can only contain one expression — no loops, no multiple statements. That restriction keeps it short.
map: transform every item
map takes a function and a sequence, then applies the function to each element.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x * x, numbers))
print(squared) # [1, 4, 9, 16]
Line by line:
map(lambda x: x * x, numbers)runs the lambda on each number: 1→1, 2→4, 3→9, 4→16.mapdoes not return a list directly; it returns a lazy map object. Wrapping it inlist()forces it to produce the actual list so we can print it.
The same result with a plain loop:
squared = []
for x in numbers:
squared.append(x * x)
map compresses that whole loop into a single readable line.
filter: keep only what matches
filter keeps the items for which the function returns True.
numbers = [5, 12, 7, 20, 3, 18]
big = list(filter(lambda x: x > 10, numbers))
print(big) # [12, 20, 18]
Here the lambda lambda x: x > 10 returns True or False for each number. filter keeps only the ones that pass the test. Again we wrap it in list() to see the result.
A practical filter: keep only even numbers.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens) # [2, 4, 6]
n % 2 == 0 is True when n divides evenly by 2. The % (modulo) operator gives the remainder, a tool you may recall from Python numbers and math.
Combining map and filter
You can chain them. Here we first keep the even numbers, then square them:
nums = [1, 2, 3, 4, 5, 6]
result = list(map(lambda x: x * x, filter(lambda n: n % 2 == 0, nums)))
print(result) # [4, 16, 36]
Read it inside-out: filter keeps [2, 4, 6], then map squares them to [4, 16, 36].
Worked example: cleaning a price list
Imagine you have raw price tags as strings, some with spaces, and you want the numeric prices above 10 pounds.
raw = [" 9.99 ", "15.00", " 3.50", "22.40 ", "11.00"]
# Step 1: turn each string into a clean number
prices = list(map(lambda s: float(s.strip()), raw))
print(prices) # [9.99, 15.0, 3.5, 22.4, 11.0]
# Step 2: keep only prices over 10
expensive = list(filter(lambda p: p > 10, prices))
print(expensive) # [15.0, 22.4, 11.0]
Walk through it:
s.strip()removes the spaces around each string;float(...)converts the cleaned text into a decimal number.mapdoes this for every element.filterthen keeps only prices greater than 10.
Breaking the task into a transform step (map) and a keep step (filter) makes the logic easy to follow and easy to test.
lambda with sorted
A very common real-world use is choosing how to sort. The sorted function accepts a key function, and a lambda is perfect for it:
people = [("Ada", 36), ("Bel", 19), ("Cy", 28)]
by_age = sorted(people, key=lambda person: person[1])
print(by_age) # [('Bel', 19), ('Cy', 28), ('Ada', 36)]
key=lambda person: person[1] tells sorted to compare people by their second element (the age). This is one of the most useful patterns you will see in real Python code.
Common mistakes
- Forgetting
list().print(map(...))shows something like<map object at 0x...>instead of values, because map and filter are lazy. - Putting statements in a lambda. A lambda cannot contain
if x:blocks, loops or assignments. Use adeffunction instead, or a conditional expression likelambda x: "big" if x > 10 else "small". - Reusing a lambda many times. If you find yourself copying the same lambda, give it a proper name with
deffor clarity.
Try it yourself
- Use
mapto convert a list of Celsius temperatures into Fahrenheit (f = c * 9/5 + 32). - Use
filterto keep only the words longer than 4 letters from["sun", "river", "cat", "mountain"]. - Sort a list of
(name, score)tuples by score from highest to lowest usingsortedwith a lambda andreverse=True.
When you are ready, compare these tools against the comprehension style in Python list comprehensions and decide which reads more clearly to you.
Quick quiz
Test yourself and earn XP
What is a lambda function?
A lambda is a short, nameless function written inline, useful for quick one-off operations.
What does map(f, items) do?
map applies the function f to each element of items, producing transformed values.
What does filter(f, items) keep?
filter keeps exactly the items for which the function returns a truthy value.
Why wrap map() or filter() in list()?
map and filter return iterator objects; calling list() forces them to produce a real list you can print.
What does lambda x: x * x do when given 4?
It squares its input, so 4 becomes 16.
FAQ
Use a lambda for a short, throwaway function you only need once, especially as an argument to map, filter or sorted. For anything longer or reused, a named def function is clearer.
They do similar jobs. Many Python programmers find list comprehensions easier to read, but map and filter are common in real code, so it helps to understand both.
No. A lambda must be a single expression. If you need multiple statements, loops or assignments, use a regular def function.
Keep exploring
More in Coding