map and filter in Python
Example of the map function in Python. It takes a function and a list and apply that function to every item on the list…
my_list = [2, 4, 3, 7, 8]
map_object = map(lambda x: x*2, my_list)
double_list = list(map_object)
print(double_list)
# [4, 8, 6, 14, 16]
Here our function multiplies each item in the list by 2, essentially doubling it. The map function returns a map object which can be turned into a list.
The filter function also takes a function and a list, but it returns a filter object instead, which similarly can be turned into a list…
my_list = [2, 4, 3, 7, 8]
filter_object = filter(lambda x: x % 2 == 0, my_list)
evens_list = list(filter_object)
print(evens_list)
# [2, 4, 8]
The function is run on each member of the list and return True or False. If False is returned, that item is filtered out. With are function testing for even, it will filter out all odd number.