Map
map(function, iterable)
- Applies a function to each object in an iterable
- Returns a map object of results ( an iterator), which can be passed to
list() or set()
- Printing out a map function directly gives an error. It needs to be converted to a list, tuple, etc. for readability.
# Program to double all numbers in a list
list_var = [1,2,3,4,5]
result = map(labmda x : x+x, list_var)
print(list(result))
# output: [2,3,6,8,10]
Filter
filter(function, iterable)
- Returns the iterable values that match the condition specified in the function.
- The function passed to filter should return a Boolean
names = ["John", "Ana", "Jack", "Kevin"]
print(list(filter(lambda x: x.startswith("J"), names)))
# ["John", "Jack"]
Reduce
-
Import it first → from functools import reduce
-
reduce(function, iterable)
-
Applies a particular function passed in its argument to all of the elements in the iterable: below are the steps:
- First two elements of sequence are picked and the result is obtained by applying the function.
- Apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
- Process continues till no more elements are left in the container.
- Final returned result is returned and printed on console.
# Sum of elements
list_var = [1, 3, 5, 6, 2, ]
print(reduce(lambda x,y:x+y,list_var))