Back
+10 XP
Concept

`map()` and `filter()` vs Comprehensions

`map(func, seq)` transforms elements. `filter(func, seq)` keeps matching ones. Modern Python prefers list comprehensions for clarity.

python
nums = [1, 2, 3, 4]
# map & filter:
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(doubled)  # [2, 4, 6, 8]
print(evens)    # [2, 4]

# 104. `map()` and `filter()` vs Comprehensions `map(func, seq)` transforms elements. `filter(func, seq)` keeps matching ones. Modern Python prefers list comprehensions for clarity: ```python nums = [1, 2, 3, 4] # map & filter: doubled = list(map(lambda x: x * 2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums)) print(doubled) # [2, 4, 6, 8] print(evens) # [2, 4] ``` Why do developers choose comprehensions? `[x * 2 for x in nums]` runs faster than `map()` with a lambda because it doesn't incur the overhead of calling a Python function object for every single item.

Checkpoint

What do `map()` and `filter()` return in Python 3?

Practice

Use `filter()` to keep only positive numbers from `[-2, 0, 5, -1, 10]`. Wrap in `list()` and print the result.

Terminal
01
Tap code blocks below to assemble
Available Blocks