MAGIC FUNCTIONS OF PYTHON

Have you ever heard about these three functions?

  • map()
  • filter()
  • reduce()

It is a part of functional programming. I call these as ‘MAGICAL FUNCTIONS’ because we can save the time and write shorter code.

map(func, *iterables)

map functions take two arguments as input. The first one is a function and second one is iterable object.

Example:

char1= [‘a’,’b’,’c’,’d’]

char2= map(str.upper, char1)

print(list(char2))

Output: >>[‘A’,’B’,’C’,’D’]

filter(func, iterable)

filter function take only two arguments, first one is a function and second one is iterable object argument function must be return Boolean value.

Example:

num=[1,2,3,4,5,6,7,8,9]

even=lambda a: if a%2 ==0

num1= map(even, num)

print(list(num1))

Output: >>[2,4,6,8]

reduce(func, iterable)

reduce function take two arguments: first one is a function which takes two arguments and second one is a iterable object.

Example:

num= [1,2,3,4,5]

sum= lambda a,b : a+b

sum1= reduce(sum,num)

print(sum1)

Output: >>15

Leave a comment

Design a site like this with WordPress.com
Get started