Map(), reduce() and filter() - all three take two arguments:

A function/lambda-expression 'f' and

A list 'l'.

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

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

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
Type "help", "copyright", "credits" or "license" for more information.
>>> 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:

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))

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