Chapter - 3
Chapter - 3
FUNCTIONAL PROGRAMMING
INTRODUCTION
Functional Programming
Functional programming is a programming paradigm that defines computation
through functions. Instead of changing the values of variables, functional
programming works only on immutable data types. Because the values of
immutable data types cannot be altered, we only work on the copies of the
original data structure. Map, filter and reduce functions in Python work precisely
in this manner — they create and work on new sets of data, leaving the original
data intact.
Higher-Order Functions
Higher-order functions are our core tool for defining computation in functional
programming. These are functions that may accept a function as an argument or
return a function as its output. In Python, reduce(), map() and filter() are some of
the most important higher-order functions. When combined with simpler
functions, they can be used to execute complex operations.
3.1 MAPPING
The python map() function is used to return a list of results after applying a given
function to each item of an iterable(list, tuple etc.)
Signature
1. map(function, iterables)
Parameters
SYNTAX:
map(function, iterables)
Here, the function defines an expression that is in turn applied to the iterables. The map function
can take user-defined functions as well as lambda functions as a parameter.
EXAMPLE:
1 def newfunc(a):
2 return a*a
4 print(x)
print(set(x))
5
OUTPUT:
<map object at 0x00000284B9AEADD8>
{16, 1, 4, 9}
As you can see, x is a map object. The next part output displays the map function taking
newfunc() as its parameter and then it applies the a*a to all the iterables. As a result, the values
of all iterables are multiplied by themselves and returned.
NOTE: The output is not in order of the values of the iterables because I have used the set()
function. You can also use the list() or tuple() functions for example:
EXAMPLE:
1 def newfunc(a):
2 return a*a
4 print(x)
print(list(x))
5
OUTPUT:
[1, 4, 9, 16]
EXAMPLE:
2 return a + b
5 print(a)
print(tuple(a))
6
OUTPUT:
(3, 6, 8)
Lambda functions within map():
Lambda functions are functions that do have any name. These functions are often supplied as
parameters to other functions. Now let us try to embed lambda functions within the map()
function. Consider the following example:
EXAMPLE:
1 tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61)
3 print(newtuple)
OUTPUT:
(8, 10, 25, 100, 57, 65, 80, 26, 76, 64)
The above output is a result of applying the lambda expression (x+3) to each item present in the
tuple.
SYNTAX:
filter(function, iterables)
Just like map(), this function can be used can also take user-defined functions as well as lambda
functions as a parameter.
EXAMPLE:
1 def func(x):
2 if x>=3:
3 return x
4 y = filter(func, (1,2,3,4))
5 print(y)
print(list(y))
6
OUTPUT:
<filter object at 0x00000284B9BBCC50>
[3, 4]
As you can see, y is the filter object and the list is a list of values that are true for the condition
(x>=3).
The lambda function that is used as a parameter actually defines the condition that is to be
checked. For example:
EXAMPLE:
2 print(list(y))
OUTPUT: [3, 4]
The above code produces the same output as the previous function.
SYNTAX:
reduce(function, iterables)
The function here defines what expression needs to be applied to the iterables. This function
needs to be imported from the functools module. For Example:
EXAMPLE:
OUTPUT: 187
In the above example, the reduce function consecutively adds each iterable present in the list and
returns a single output.
The map(), filter() and reduce() functions in Python can be used along with each other.
310 Sec
3.4 Lambda Functions
Python Lambda function is known as the anonymous function that is defined without a name.
Python allows us to not declare the function in the standard manner, i.e., by using the def keyword.
Rather, the anonymous functions are declared by using the lambda keyword. However, Lambda
functions can accept any number of arguments, but they can return only one value in the form of
expression.
The anonymous function contains a small piece of code. It simulates inline functions of C and
C++, but it is not exactly an inline function.
Syntax
It can accept any number of arguments and has only one expression. It is useful when the function
objects are required.
Example 1
Output:
In the above example, we have defined the lambda a: a+10 anonymous function where a is an
argument and a+10 is an expression. The given expression gets evaluated and returned the result.
The above lambda function is same as the normal function.
1. def x(a):
2. return a+10
3. print(sum = x(10))
Using map(),filter() and reduce() functions along with each other:(using
lambda function)
When you do this, the internal functions are first solved and then the outer
functions operate on the output of the internal functions.
Let us first try passing the filter() function as a parameter to the map() function.
EXAMPLE:
2 print(list(c))
OUTPUT: [6, 8]
If you filter out integers greater than or equal to 3 from the given tuple, you get
[3,4] as the result. Then if you map this using(x+x) condition, you will get [6,8],
which is the output.
When you use the map() function within filter() function, the iterables are first
operated upon by the map function and then the condition of filter() is applied to
them.
2 print(list(c))
OUTPUT: [4, 6, 8]
2 print(d)
OUTPUT: 14
The output is a result of [6,8] which is the result of the internal map() and filter()
functions.
As per the above syntax, the list comprehension syntax contains three
parts: an expression, one or more for loop, and optionally, one or
more if conditions. The list comprehension must be in the square
brackets []. The result of the first expression will be stored in the new
list. The for loop is used to iterate over the iterable object that
optionally includes the if condition.
even_nums = []
for x in range(21):
if x%2 == 0:
even_nums.append(x)
print(even_nums)
Output
List comprehension works with string lists also. The following creates
a new list of strings that contains 'a'.
['Ram', 'Mohan']