What are Built-in Map/Reduce functions in Python?
The map is a built-in function that takes a function and an iterable like a list(or)tuple(or)set and runs the given function on each element in that and returns a new list with the returned values.
Example
let's say we have a list of numbers and we want a new list with squares of these numbers
my_list=[1,2,3]
def square(num):
return num**2
in a way we use for loop
my_list=[1,2,3]
def square(num):
return num**2
squared=[]
for x in my_list:
squared.append(square(x))
now we use our function Map to do this in one line
squared=map(square,my_list)
print(type(squared))
the filter is a built-in function that takes a function and an iterable like a list and returns a new iterable with only those values for which the function returns True...
Example
let us say we have a list of numbers and we want to retain only odd numbers in it.
my_list=[1,2,3,4,5,6,7,8]
def is_odd(num):
return num%2==1
now we use the filter function
filtered=filter(is_odd,my_list)
print(type(filtered))
#<class 'filter'>
we can iterate over the result using for loop
for x in filtered:
print(x)
#1
#3
#5
#7
I want to convert it into a list so
my_filtered_list=list(filtered)
print(my_filtered_list)
#[]
Example
my_list=['john','mary','doe','jane']
def lower(str):
return str.lower()
result=map(lower,my_list)
print(type(result))
#<class 'map'>
result_list=list(result)
print(len(result_list))
#4
print(result_list[3])
#jane
Try it Yourself
write a Python function called filter_list(my_list) which using the filter function to filter the input lists of strings so that only those strings which have the sub-string 'ing' are returned as a list. and also add the 'ing' to the remaining strings using the map function.
my_list=['run','running','code','coding','flinger','ringing']
output_list=filter_list(my_list)
#out_list should be filtered to have only: ing listed.
Did you find this article valuable?
Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!