Recently, I decided to learn how to use the functional programming tools provided by Python.
Truth is, it’s interestingly strong.
The whole concept consists of using 3 built-in functions (map, filter, reduce), lambda functions and of course the beloved List Comprehensions.
In order of appearance :
map (function, sequence) : It applies function on every item of the sequence.
You can even provide a function which takes two arguments and use it like this :
map (function, seq1, seq2)
filter (function, sequence) : It returns a sequence of the items which have a function (Item) == True value.
reduce (function, sequence) : It applies the function (2 arguments) to the first two items of the sequence, and then to the result and the third etc…
List comprehensions :
This a powerful feature of Python.
I will explain it by an example :
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x**3 for x in a]
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
Lambda functions :
With lambda functions you can create anonymous functions on the fly.
For example, the normal definition of a function is :
def f(n): return n**3
With lambda functions :
f = lambda n: n**3
In both cases, we use like this :
An example of using lambda functions with the map function would be like this :
>>> map(lambda x: x**3, a)
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729
This is exactly the same as the example in list comprehensions.
So, with all the above we have a whole new range of tools for dealing with lists.