Nearby lessons

74 of 159

Python - map() and filter() Functions

📌 What You Will Learn
  • Describe the purpose of map() and filter()
  • Use functions and lambda expressions with both tools
  • Convert lazy results to lists
  • Chain transformations and filtering
  • Choose a readable alternative when a comprehension is clearer

Functional transformations

map() and filter() accept a callable and an iterable. They are useful for concise data-processing pipelines.

map() syntax

Use map(function, iterable). The function is called once for each item.

Mapping with a named function

🐍Code Cell
1def double(number):
2 return number * 2
3 
4result = list(map(double, [1, 2, 3]))
5print(result)
Output
[2, 4, 6]

Mapping with lambda

🐍Code Cell
1numbers = [1, 2, 3]
2result = list(map(lambda n: n ** 2, numbers))
3print(result)
Output
[1, 4, 9]

filter() syntax

Use filter(predicate, iterable). Items are included when the predicate returns a truthy value.

Filtering even numbers

🐍Code Cell
1numbers = [1, 2, 3, 4, 5, 6]
2evens = list(filter(lambda n: n % 2 == 0, numbers))
3print(evens)
Output
[2, 4, 6]

Mapping and filtering together

🐍Code Cell
1numbers = [1, 2, 3, 4]
2result = list(map(lambda n: n * 10, filter(lambda n: n % 2 == 0, numbers)))
3print(result)
Output
[20, 40]

Lazy results and readability

In Python 3, neither function creates a list automatically. Use list() for display or repeated access. For simple expressions, a list comprehension may be easier for readers to understand.

📝 Key Takeaways
  • map() applies a function to every item
  • filter() keeps items for which a predicate is true
  • Both return lazy iterators in Python 3
  • list() materializes their results
  • Comprehensions can express simple map/filter operations clearly

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8