Map, Filter, Reduce and Zip in Python
A 2 minute read on sequence processing functions for clean programming.
Map, filter, reduce and zip are sequence processing functions, heavily used in functional programming. This saves you from writing an explicit loop like while or for.
The map
and filter
function each apply some function to a sequence to create a new sequence.
Example of Map:
I’ve created a function called string edit which accepts a string and lowercases the text and replaces ‘the’ with ‘ ’.
def string_edit(text):
return text.lower().replace(‘the’,’’)string_list=[
'The best apps download superpowers to your smartphone.',
' The Verge covers the new and noteworthy Android apps, iPhone apps, and games',
'Highlighting great design, impressive utility, and novel features.',
'If it belongs on your phone, youll find it on The Verge.'
]x=list(map(string_edit,string_list))print(x)
Output:
[' best apps download superpowers to your smartphone.', ' verge covers new and noteworthy android apps, iphone apps, and games', 'highlighting great design, impressive utility, and novel features.', 'if it belongs on your phone, youll find it on verge.']
This code would have been clunky if we had used For loop with the function.
Example of Filter:
div3=list(filter(lambda n: n%5 == 0,range(20)))print(div3)
Output:
[0, 5, 10, 15]
Example of Reduce:
The reduce
function applies a function which will reduce the sequence to a single value. In python, reduce comes under the functools library.
from functools import reducereduce(lambda x, y: x+y, range(100))
Output:
4950
Example of Zip:
The zip
function mix/joins values from lists to create a list of tuples.
animals=[‘Cat’, ‘Dog’, ‘Mouse’, ‘Elephant’, ‘Hamster’]number_of_animals=[3,4,6,1,5]print(list(zip(animals,number_of_animals)))
Output:
[(‘Cat’, 3), (‘Dog’, 4), (‘Mouse’, 6), (‘Elephant’, 1), (‘Hamster’, 5)]