Explain map, filter, reduce and zip functions?

map:
  • It is a built-in higher-order function that operates on iterable.
  • Functions that can accept other functions as arguments and return function to the caller is known as Higher-order functions.
  • It takes a function and an iterable as arguments and returns a new iterable with the function applied to each item of iterable.
filter:
  • It filters an iterable by removing items that don’t match a predicate.
  • A predicate is a function that returns a Boolean.
reduce:
  • It continuously applies the function to sequence and returns a single value.
zip:
  • It takes two equal-length collections and merges them together in pairs.
Example:

nums = [ 11,22,33,44,55 ]

list1  = [ 1,2,3  ]

list2 = [ ‘a’,’b’,’c’ ]

>> zip( list1 , list2 ) # [(1, 'a'), (2, 'b'), (3, 'c')]


>> res = list( filter ( lambda x : x % 2 == 0 , nums ) )

>> print(res) # [ 22, 44 ]


>> print(map(lambda x : x + 5 , nums))

>> # prints [16, 27, 38, 49, 60]

>> print(reduce(lambda x,y : x + y , list1)) # prints 6

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?