Functional Programming In Python
Functional programming divides a larger problem into a set of smaller functions. A function takes some inputs and produces some outputs. Functions do not have any internal state that influences the output generated for a given input. There are few special types of functions provided by Python, such as lambda, map, reduce.
The lambda function
Lambda function is an anonymous function to do a small task. A Lambda function is very much like an inline function available in C/C++. The parameters of the lambda function are defined to the left of the colon. The function body is defined as the right of the colon. The result of running the function body is (implicitly)returned.
for example
res= lambda x: x*x print(res(6)) Output: 36
The Map function
We can create a map that takes a function and a collection as input, to generate a new empty collection to run the function on each item individually of the input collection, and inserts each return value into the collection. This map finally returns this newly created collection.
For example
str_lengths=map(len, ['JavaScript','Java','Python']) print(str_lengths) Output: [10, 4, 6]
The Reduce Function
A reduce() accepts a function with a collection of elements. It returns a combined value after applying the input function to all of these elements. For example, the following reduce returns the summation of all the numbers in the collection.
import functools total = functools.reduce(lambda a, x: a + x, [0, 1, 2, 3, 4]) print(total) Output: 10
The Filter Function
A filter accepts a function and a collection. and returns a collection of all the elements for which the function returns true.
arr=[1,2,3,4,5,6] for i in filter(lambda x:x>4,arr): print(i) Output: 5 6