Zip, Map, Filter and Reduce operations in Python

Gurpreet Dhami
Lets Learn Python
Published in
1 min readMay 21, 2024

--

Zip()

Like a physical zip, it basically pulls elements from multiple iterators and return the tuples.

list_a= [1,2,3,4]
list_b = ['a','b', 'c']

zipper = zip(list_a, list_b)
print(list(zipper))

>> Output
[(1,), (2,), (3,), (4,)]
[(1, 'a'), (2, 'b'), (3, 'c')]

If the iterators have unequal length, then then it stop at the stortest of all iterators.

Map()

Map is similar to zip, just that along with iterating over the elements, it applies a tranformation.

numbers = [1,2,3,4]
def square(number:int):
return number**2

print(list(map(square,numbers)))

Filter()

As the name suggests, it filters out the elements from an iterable based on specific condition. So it will return the element if the condition is True.

list_nums = [1,2.0,4,5.0]

def check_ints(number):
if type(number) == int:
return True
else:
return False

print(list(filter(check_ints,list_nums)))

>> [1, 4]

Reduce()

Reduce is similar to map, but it does the transformation cumulatively on each subsequent output and creates a final output.

It does the following operations

  • First takes 1st two elements and perform the transformation.
  • Then pick the partial sum and take third element and again do the transformation till the list exhausts.
from functools import reduce
list_a = [11, 2, 3, 4]

sum_a=0
def sum_list(num, num1):
return num + num1

print(reduce(sum_list, list_a))

>>20

--

--