Key Differences Between map
and filter
Purpose:
map
: Transforms each element of an iterable using a function and returns an iterator with the transformed elements.filter
: Filters elements of an iterable using a function and returns an iterator with elements for which the function returnsTrue
.
Function Return Type:
map
: The function passed tomap
can return any type of value.filter
: The function passed tofilter
must return a boolean value.
Output Length:
map
: The length of the output iterable is the same as the input iterable.filter
: The length of the output iterable may be less than or equal to the input iterable, depending on how many elements satisfy the condition.
Combining map
and filter
You can combine map
and filter
to first filter elements and then apply a transformation. This approach is useful for more complex data processing tasks.
The map
Function
The map
function applies a given function to all items in an input iterable (e.g., list, tuple) and returns a map object (an iterator) with the results.
Parameters:
function
: A function that takes one argument and returns a value.iterable
: An iterable (e.g., list, tuple) whose elements will be passed to the function.
# Syntax
map(function, iterable)
# Example
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))
# Output
[1, 4, 9, 16, 25]
The filter
Function
The filter
function constructs an iterator from elements of an iterable for which a function returns True
.
Parameters:
function
: A function that takes one argument and returns a boolean (True
orFalse
).iterable
: An iterable (e.g., list, tuple) whose elements will be tested by the function.
# Syntax
filter(function, iterable)
# Example
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
# Output
[2, 4, 6]
# map and filter combined
def is_positive(x):
return x > 0
def increment(x):
return x + 1
numbers = [-2, -1, 0, 1, 2, 3]
positive_numbers = filter(is_positive, numbers)
incremented_numbers = map(increment, positive_numbers)
print(list(incremented_numbers))