🎓 A1Learner
🔍
0 of 52 lessons completed

Python Chaining map() and filter()

A chain runs map() and filter() in one line. The data flows from one step to the next.

Filter first, then change

filter() keeps the even numbers. map() then doubles only those.

nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 2, filter(lambda n: n % 2 == 0, nums))))

Change first, then filter

map() turns each word into its length. filter() then keeps the lengths above 3.

words = ["fig", "pear", "banana", "kiwi"]
print(list(filter(lambda n: n > 3, map(len, words))))

Two spellings, one result

The chain and the comprehension give the same list. Pick the spelling that reads clearer.

nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 2, filter(lambda n: n % 2 == 0, nums))))
print([n * 2 for n in nums if n % 2 == 0])

Example

raw = [" 88 ", " 95", "71 ", " 92 ", " 64"]
clean = list(map(str.strip, raw))
scores = list(map(int, clean))
passing = list(filter(lambda n: n >= 80, scores))
print("Clean:", clean)
print("Scores:", scores)
print("Passing:", passing)

Key points

  • Chain: map() and filter() joined in one line, so data flows step by step
  • The innermost call runs first. Its result feeds the next call.
  • Use filter() first when some items should never reach the next step
  • Use map() first when every item needs changing before the test
  • Two steps stay readable in one line. Three steps want a helper function or a loop.
  • A list comprehension can do the same job. map() and filter() are a second spelling of that idea.

In this example, the raw list holds score text with stray spaces. The first map() strips the spaces. The second map() turns each clean string into a number. filter() then keeps the scores of 80 or more. Each printout shows one step, so the reader can check the data after every change.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

In list(map(str.upper, filter(lambda w: len(w) > 3, words))), which step runs first?