[Python] 3.5. Lambda with map, reduce, filter on Python

Lambda

The lambda is from Lisp of AutoCAD or AI. In a word, It is like an one line function.

How to use

lambda parameter : expression

ex1)
>>> def add(x, y)
… return x + y
>>> add(10, 20)
30

is same with

>>> (lambda x, y: x + y)(10, 20)
30

map

How to use

map(function, list)

ex2)
>>> map(lambda x: x ** 2, range(5)) # python2
[0, 1, 4, 9, 16]
>>> list(map(lambda x: x ** 2, range(5))) # python2 & python3

Reduce

How to use

reduce(function, string or list or tuple)

ex3)
>>> from functools import reduce # python 3
>>> reduce(lambda x, y: x + y, [0, 1, 2, 3, 4])
10

cf) (lambda x, y: x+y) == (operator.add)

filter

How to use

filter(function, list)

ex4)
>>> filter(lambda x: x < 5, range(10)) # python2
[0, 1, 2, 3, 4]
>>> list(filter(lambda x: x < 5, range(10))) # python3
[0, 1, 2, 3, 4]

reference