There are 3 unique functions defined in python to help the dev write some really good code. Mainly Map, Reduce & Filter. I will also discuss about Lambda and some other techniques in the next blogs.
MAP
It’s a very special functions that maps a sequence to a method and create a new sequence. To be specific it takes the function as first argument and the sequence as second argument, kind of iterate over the sequence and process the each element in the parsed function. This is almost equal to running a Loop, but in a very optimum and pythonic way which is already defined some where and you do not have to reinvent the wheel.
eg, Suppose i want to convert each element of [1, 2, 3, 4] into string. If i do direct typecast to str it will also convert the [] into str. So the possible way is loop through each element of the list and typecast it or you can simply do it in one line like below,
>>> a = [1, 2, 3, 4]
>>> b = map(str, a) # str is a builtin typecasting method in python
>>> print b
[‘1’, ‘2’, ‘3’, ‘4’]
REDUCE
Same way we have reduce method in python, which runs and incredibly fast reduction algorithm to reduce whole sequence into a single number. Here the first argument is method, second argument is a sequence. You can also provide an initial argument or offset value for the same, Let me explain how in the below code.
>>> a = [1, 2, 3, 4]
>>> def sum(x, y):
. . . : return x + y
>>> b = reduce(sum, a)
>>> b
10
>>> c = reduce(sum, a, 10)
>>> c
20
reduce(sum, a) takes the first two elements of the list, calculates the sum passes the sum and the third element again into the reduce. If you pass an empty list into it it should break.
But in reduce(sum, a, 10) it will pass 10 as the initial parameter ans keeps summing it. It will not break even with an empty list.
FILTER
Now Filter is exactly same as map except it only returns the true values of the condition provided. Let me give you an example.
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> def is_even(x):
. . . : if x%2==0:
. . . : return x
>>> map(is_even, a)
[None, 2, None, 4, None, 6, None, 8]
>>> filter(is_even, a)
[2, 4, 6, 8]
** Filter simply ignores None or False values, Where as Map doesn’t.