0% found this document useful (0 votes)
20 views11 pages

Chapter - 3

Chapter 3

Uploaded by

bidaatmaslake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views11 pages

Chapter - 3

Chapter 3

Uploaded by

bidaatmaslake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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

Python map() Function

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

function- It is a function in which a map passes each item of the iterable.

iterables- It is a sequence, collection or an iterator object which is to be mapped.


Return

It returns a list of results after applying a given function to each item of an


iterable(list, tuple etc.)

3.1 What are map(), filter() and reduce() functions in


Python?
As mentioned earlier, map(), filter() and reduce() are inbuilt functions of Python. These functions
enable the functional programming aspect of Python. In functional programming, the arguments
passed are the only factors that decide upon the output. These functions can take any other
function as a parameter and can be supplied to other functions as parameters as well

3.1The map() function:


The map() function is a type of higher-order. As mentioned earlier, this function takes another
function as a parameter along with a sequence of iterables and returns an output after applying
the function to each iterable present in the sequence. Its syntax is as follows:

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.

Using user-defined and Lambda Functions within:


User-defined functions within map():
The map() function can take user-defined functions as parameters. The parameters of these
functions are exclusively set by the user or the programmer. For example:

EXAMPLE:

1 def newfunc(a):

2 return a*a

3 x = map(newfunc, (1,2,3,4)) #x is the map object

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

3 x = map(newfunc, (1,2,3,4)) #x is the map object

4 print(x)

print(list(x))
5

OUTPUT:

<map object at 0x00000284B9AEA940>

[1, 4, 9, 16]

EXAMPLE:

1 def func(a, b):

2 return a + b

4 a = map(func, [2, 4, 5], [1,2,3])

5 print(a)

print(tuple(a))
6

OUTPUT:

<map object at 0x00000284B9BA1E80>

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

2 newtuple = tuple(map(lambda x: x+3 , tup))

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.

3.2 The filter() function:


The filter() function is used to create an output list consisting of values for which the function
returns true. The syntax of it is as follows:

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

Using lambda within filter():

The lambda function that is used as a parameter actually defines the condition that is to be
checked. For example:

EXAMPLE:

1 y = filter(lambda x: (x>=3), (1,2,3,4))

2 print(list(y))

OUTPUT: [3, 4]

The above code produces the same output as the previous function.

3.3 The reduce() function:


The reduce() function, as the name describes, applies a given function to the iterables and returns
a single value.
The syntax of this function is as follows:

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:

1 from functools import reduce

2 reduce(lambda a,b: a+b,[23,21,45,98])

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.

The syntax to define an anonymous function is given below.

Syntax

1. lambda arguments: expression

It can accept any number of arguments and has only one expression. It is useful when the function
objects are required.

OOPs Concepts in Java

Consider the following example of the lambda function.

Example 1

1. # a is an argument and a+10 is an expression which got evaluated and returned.


2. x = lambda a:a+10
3. # Here we are printing the function object
4. print(x)
5. print("sum = ",x(20))

Output:

<function <lambda> at 0x0000019E285D16A8>


sum = 30

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.

Using filter() within map():


The code given below first checks for the condition (x>=3) to be true for the
iterables. Then, the output is mapped using the map() function.

EXAMPLE:

1 c = map(lambda x:x+x,filter(lambda x: (x>=3), (1,2,3,4)))

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.

Using map() within filter():

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.

1 c = filter(lambda x: (x>=3),map(lambda x:x+x, (1,2,3,4))) #lambda x: (x>=3)

2 print(list(c))

OUTPUT: [4, 6, 8]

Using map() and filter() within reduce():


The output of the internal functions is reduced according to the condition supplied
to the reduce() function.
EXAMPLE:

1 d = reduce(lambda x,y: x+y,map(lambda x:x+x,filter(lambda x: (x>=3), (1,2,3,4))))

2 print(d)

OUTPUT: 14

The output is a result of [6,8] which is the result of the internal map() and filter()
functions.

3.5 Python List Comprehension


List comprehension in Python is an easy and compact syntax for
creating a list from a string or another list. It is a very concise way to
create a new list by performing an operation on each item in the
existing list. List comprehension is considerably faster than processing
a list using the for loop.st Comprehension Syntax:

Syntax:-[expression for element in iterable if condition]

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.

Suppose we want to find even numbers from 0 to 20 then we can do


it using a for loop, as shown below:

Example: Create List of Even Numbers without List Comprehension

even_nums = []
for x in range(21):
if x%2 == 0:
even_nums.append(x)
print(even_nums)
Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


The same result can be easily achieved using a list comprehension
technique shown below.

Example: Create List of Even Numbers with List Comprehension

even_nums = [x for x in range(21) if x%2 == 0]


print(even_nums)
Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

In the above example, [x for x in range(21) if x%2 == 0] returns a new list


using the list comprehension. First, it executes the for loop for x in
range(21) if x%2 == 0. The element x would be returned if the specified
condition if x%2 == 0 evaluates to True. If the condition evaluates to
True, then the expression before for loop would be executed and
stored in the new list. Here, expression x simply stores the value
of x into a new list.

List comprehension works with string lists also. The following creates
a new list of strings that contains 'a'.

Example: List Comprehension with String List

names = ['Steve', 'Bill', 'Ram', 'Mohan', 'Abdul']


names2 = [s for s in names if 'a' in s]
print(names2)
Output

['Ram', 'Mohan']

Above, the expression if 'a' in s returns True if an element contains a


character 'a'. So, the new list will include names that contain 'a'.

The following example uses a list comprehension to build a list of


squares of the numbers between 1 and 10.

Example: List Comprehension

squares = [x*x for x in range(11)]


print(squares)
Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Above, a for loop for x in range(11) is executed without any if condition.


The expression before for loop x*x stores the square of the element in
the new list.
ADVERTISEMENT

List Comprehension with Multiple if Conditions


We can use nested if conditions with a list comprehension.

Example: List Comprehension

nums = [x for x in range(21) if x%2==0 if x%5==0]


print(nums)
Output

[0, 10, 20]

You might also like