Data Structuresand Algorithms Good OldJava AdvancedInterview Topics Cloud andDatabases Web Designand Development Must-knowTools Good ToKnow

## Map-Reduce and Filter

Map(), reduce() and filter() - all three take two arguments:
1. A function/lambda-expression 'f' and
2. A list 'l'.

1. Map: Applies 'f' to each element of 'l'

2. Reduce: Takes two elements from 'l' sequentially and applies 'f' to them.
So 'f' used in reduce() must accept two arguments.

3. Filter: Filters elements from 'l' which do not satisfy 'f'.
So 'f' used in filter() must return a boolean.

```
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32

>>> cube = lambda a: a*a*a
>>> cube(3)
27

# map() has started returning an iterator since python version 3
>>> map (cube, [1,2,3])
<map object at 0x000000000292E3C8>

# To convert the iterator to a list, use list() as follows:
>>> list (map (cube, [1,2,3]))
[1, 8, 27]

# The iterator can also be traversed using next():
>>> i = map (cube, [1,2,3])
>>> next(i)
1
>>> next(i)
8
>>> next(i)
27
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

# Since python version 3, reduce() has been moved to functools
>>> import functools
>>> functools.reduce( lambda x,y: x+y, [1,2,3])
6

# filter() also returns an iterator and can be converted using list() or used with next()
>>> list (filter (lambda x: x%2, [1,2,3,4]))
[1, 3]

```

A simple prime number function in python can be written in just a few lines of code:
```
>>> nums = list(range(2, 50))
[
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49
]

>>> for i in range(2, 8):
...   nums = list(filter(lambda x: x == i or x % i, nums))

>>> nums
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

```
Compare this with the equivalent code in Java.
BTW, the above algorithm is called Sieve of Eratosthenes algorithm.

The above algorithm is understood better if you unwind the loop:
```nums = list(filter(lambda x: x == 2 or x % 2, nums))
nums = list(filter(lambda x: x == 3 or x % 3, nums))
nums = list(filter(lambda x: x == 4 or x % 4, nums))
nums = list(filter(lambda x: x == 5 or x % 5, nums))
nums = list(filter(lambda x: x == 6 or x % 6, nums))
nums = list(filter(lambda x: x == 7 or x % 7, nums))
```

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

 Name: Email: (Your email is not shared with anybody) Comment: