Junior — Middle
What is the difference between map and filter functions when processing data collections?
sobes.tech AI
Answer from AI
The map and filter functions are used for processing collections but serve different purposes:
-
map(function, iterable) — applies the function to all elements and returns an iterator with the results.
-
filter(function, iterable) — filters elements, passing only those for which the function returns
True.
Example:
numbers = [1, 2, 3, 4, 5]
# map: square each element
squares = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
# filter: select only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
In summary:
maptransforms each element.filterselects elements based on a condition.