map:
The map() function applies a specified function to each item in an iterable (like a list or tuple)
and returns a new iterable containing the transformed items.
filter:
The filter() function filters elements from an iterable based on a condition defined by a function, returning a new iterable with only the elements that satisfy the condition.
Step-by-Step Process
Map:
Define a function or use a lambda that specifies the transformation to apply to each element in an iterable.
Pass the function and the iterable to map(function, iterable) to apply the transformation.
Convert the map object to a list or another collection type to access or display the results.
Filter:
Define a function or use a lambda that specifies the condition to filter elements in an iterable.
Pass the function and the iterable to filter(function, iterable) to apply the condition.
Convert the filter object to a list or another collection type to access or display the filtered results.
Sample Code
#Using Map()
# Square each number in a list
numbers = [1, 2, 3, 4, 5]
def square(num):
return num ** 2
squared_numbers = map(square, numbers)
print("Output for map():")
print("Squared Numbers:", list(squared_numbers))
print()
#Using Filter()
#Filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6]
def is_even(num):
return num % 2 == 0
even_numbers = filter(is_even, numbers)
print("Output for filter():")
print("Even Numbers:", list(even_numbers))