0% found this document useful (0 votes)
27 views

PSC-UNIT1-3-Higher Order Functions in Python

Uploaded by

Khushbu Maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

PSC-UNIT1-3-Higher Order Functions in Python

Uploaded by

Khushbu Maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

 A function is called

Higher Order Function


if it contains other functions as a parameter or returns a function
as an output i.e, the functions that operate with another function
are known as Higher order Functions. It is worth knowing that
this higher order function is applicable for functions and
methods as well that takes functions as a parameter or returns a
function as a result. Python too supports the concepts of higher
order functions.
Properties of higher-order functions:

A function is an instance of the Object type.


You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, …

Functions as objects

In Python, a function can be assigned to a variable. This assignment does not call the
function, instead a reference to that function is created. Consider the below example, for
better understanding.

Start coding or generate with AI.

# Python program to illustrate functions


# can be treated as objects
def shout(text):
return text.upper()
print(shout('Hello'))
# Assigning function to a variable
yell = shout
print(yell('Hello'))
HELLO
HELLO

1 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

In the above example, a function object referenced by



shout and creates a second name pointing to it, yell.

Passing Function as an argument to other function

Functions are like objects in Python, therefore, they can


be passed as argument to other functions. Consider the
below example, where we have created a function greet
which takes a function as an argument.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)
greet(shout)
greet(whisper)
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

 Returning function

As functions are objects, we can also return a function


from another function. In the below example, the
create_adder function returns adder function.

# Python program to illustrate functions


# Functions can return another function
def create_adder(x):
def adder(y):
return x + y
return adder

2 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

add_15 = create_adder(15)
print(add_15(10))
25

A higher-order function is a function that takes another function


as a parameter

They are “higher-order” because it’s a function of a function

Examples
Map

Reduce

Filter

Lambda works great as a parameter to higher-order functions if


you can deal with its limitations

 map

It is a function to which map passes each element of given


iterable.
iter : It is a iterable which is to be mapped.

You can pass one or more iterable to the map() function.

The returned value from map() (map object) then can be passed to functions like list() (to
create a list), set() (to create a set) .

Start coding or generate with AI.

3 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
nums = list(map(lambda x : x % 5, nums))
print(nums)
#[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]
[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]

org_list = [1, 2, 3, 4, 5]

# define a function that returns the cube of `num`


def cube(num):
return num**3

fin_list = list(map(cube, org_list))


print(fin_list) # [1, 8, 27, 64, 125]
[1, 8, 27, 64, 125]

fin_list = list(map(lambda x:x**3, org_list))


print(fin_list) # [1, 8, 27, 64, 125]
[1, 8, 27, 64, 125]

base = [1, 2, 3, 4]
power = [1, 2, 3, 4]

result = list(map(pow, base, power))


print(result) # [1, 4, 27, 256]
[1, 4, 27, 256]

people = ["lokesh", "bob", "tom", "developer"]


up = list(map(lambda x: x.upper(), people))
print(up)
Output: ['LOKESH', 'BOB', 'TOM', 'DEVELOPER']
['LOKESH', 'BOB', 'TOM', 'DEVELOPER']

names = [
{'first': 'lokesh', 'last': 'sharma'},
{'first': 'Astha', 'last': 'verma'},
{'first': 'jiu', 'last': 'rai'}
]
first_names = list(map(lambda x: x['first'], names))
print(first_names)
Output: ['lokesh', 'Astha', 'jiu']
['lokesh', 'Astha', 'jiu']

Goal: given a list of three dimensional points in the form of tuples, create a new list consisting
of the distances of each point from the origin

Loop Method: - distance(x, y, z) = sqrt(x2 + y2 + z**2) - loop through the list and add results to
a new list

4 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

a new list

from math import sqrt

points = [(2, 1, 3), (5, 7, -3), (2, 4, 0), (9, 6, 8)]

def distance(point) :
x, y, z = point
return sqrt(x**2 + y**2 + z**2)

distances = list(map(distance, points))


print(distances)

[3.7416573867739413, 9.1104335791443, 4.47213595499958, 13.45362404707371]

 �lter(function, iterable)

The �lter runs through each element of iterable (any iterable


object such as a List or another collection)
It applies function to each element of iterable If function returns True for that element then
the element is put into a List

This list is returned from �lter in versions of python under 3 In python 3, �lter returns an
iterator which must be cast to type list with list()

Syntax: �lter(fun, Iter)

fun: function that tests if each element of a sequence true or not.

Iter: Iterable which needs to be �ltered.

 Example 1: Filter out even and odd numbers from list

seq = [0, 1, 2, 3, 4, 5]
# result contains odd numbers of the list

5 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

result = filter(lambda x: x % 2, seq)


print(list(result))
result = map(lambda x: x % 2, seq)
print(list(result))
# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))
result = map(lambda x: x % 2==0, seq)
print(list(result))
[1, 3, 5]
[0, 1, 0, 1, 0, 1]
[0, 2, 4]
[True, False, True, False, True, False]

nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]

nums = list(filter(lambda x : x != 0, nums))

print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]

[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]

#A dictionary Users(twitter database) is given in which we have username and tweets.

users = [
{"username": 'samuel', "tweets": ["i love cake", "i am good"]},
{"username": 'andy', "tweets": []},
{"username": 'kumal', "tweets": ["India", "Python"]},
{"username": 'sam', "tweets": []},
{"username": 'lokesh', "tweets": ["i am good"]},
]

#Filter out Users which dont have any tweets/Inactive Users

inactive_users = list(filter(lambda a:not a['tweets'], users))


print(inactive_users)

[{'username': 'andy', 'tweets': []}, {'username': 'sam', 'tweets': []}]

#Filter inactive users with just username in uppercase.

inactive_users=list(map(lambda x:x["username"].upper(),
filter(lambda a:not a['tweets'], users)))
print(inactive_users)
['ANDY', 'SAM']

#Return a new list with the string “your name is” + name ,but only if length of name i

names=['lokesh','lassie','blue','to']
new=list(map(lambda name:f"your name is {name}",

6 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

filter(lambda x:len(x)>4,names)))
print(new)
['your name is lokesh', 'your name is lassie']

bold text#3.Reduce:

Double-click (or enter) to edit

The reduce() function accepts a function and a sequence and



returns a single value calculated as follows:

Step-1:Initially, the function is called with the �rst two items from the sequence and the result
is returned.

Step-2: The function is then called again with the result obtained in step 1 and the next value
in the sequence. This process keeps repeating until there are items in the sequence.

#Example-1 Find Multiply of all elements in list


from functools import reduce
seq=[2,3,4,5,6]
multiply=reduce(lambda a,b:a*b,seq)
print(multiply)
720

Output:720

First: It takes 2,3 and return 6

Second: It takes 6 and 4, retuen 24

Third: It takes 24 and 5, return 220

Fourth: It takes 220 and 6, return 720

All elements in sequence are over so it returns 720 as output.

# python code to demonstrate working of reduce()


# importing functools for reduce()
import functools

7 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

import
# initializing list
lis = [1, 3, 5, 6, 2]
# using reduce to compute sum of list
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))
# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))

The sum of the list elements is : 17


The maximum element of the list is : 6

Start coding or generate with AI.

nums = [1, 2, 3, 4, 5, 6, 7, 8]

nums = list(reduce(lambda x, y : (x, y), nums))

print(nums)

[((((((1, 2), 3), 4), 5), 6), 7), 8]

 Decorators in Python

Decorators are a very powerful and useful tool in Python since it


allows programmers to modify the behaviour of a function or
class. Decorators allow us to wrap another function in order to
extend the behaviour of the wrapped function, without
permanently modifying it. But before diving deep into decorators
let us understand some concepts that will come in handy in
learning the decorators.

Start coding or generate with AI.

 First Class Objects

In Python, functions are �rst class objects which means that


functions in Python can be used or passed as arguments.

8 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

Properties of �rst class functions:


• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables, lists, …

# Python program to illustrate functions


# can be treated as objects
def shout(text):
return text.upper()

print(shout('Hello'))

yell = shout

print(yell('Hello'))

HELLO
HELLO

In the above example, we have assigned the function shout to


a variable. This will not call the function instead it takes the

function object referenced by a shout and creates a second
name pointing to it, yell.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return text.upper()

def whisper(text):
return text.lower()

def greet(func):
# storing the function in a variable
greeting = func("""Hi, I am created by a function passed as an argument."""
print (greeting)

greet(shout)
greet(whisper)

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.


hi, i am created by a function passed as an argument.

9 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

hi, i am created by a function passed as an argument.

In the above example, the greet function takes another


function as a parameter (shout and whisper in this case). The

function passed as an argument is then called inside the
function greet.

# Python program to illustrate functions


# Functions can return another function

def create_adder(x):
def adder(y):
return x+y

return adder

add_15 = create_adder(15)

print(add_15(10))

25

In the above example, we have created a function inside of


 another function and then have returned the function created
inside.

The above three examples depict the important concepts that


are needed to understand decorators. After going through them
let us now dive deep into decorators.

# defining a decorator
def hello_decorator(func):

# inner1 is a Wrapper function in


# which the argument is called

# inner function can access the outer local


# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")

# calling the actual function now

10 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

# calling the actual function now


# inside the wrapper function.
func()

print("This is after function execution")

return inner1

# defining a function, to be called inside wrapper


def function_to_be_used():
print("This is inside the function !!")

# passing 'function_to_be_used' inside the


# decorator to control its behaviour
function_to_be_used = hello_decorator(function_to_be_used)

# calling the function


function_to_be_used()

Hello, this is before function execution


This is inside the function !!
This is after function execution

# importing libraries
import time
import math

# decorator to calculate duration


# taken by any function.
def calculate_time(func):

# added arguments inside the inner1,


# if function takes any arguments,
# can be added like this.
def inner1(*args, **kwargs):

# storing time before function execution


begin = time.time()

func(*args, **kwargs)

# storing time after function execution


end = time.time()
print("Total time taken in : ", func.__name__, end - begin)

return inner1

# this can be added to any function present,


# in this case to calculate a factorial

11 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

# in this case to calculate a factorial


@calculate_time
def factorial(num):

# sleep 2 seconds because it takes very less time


# so that you can see the actual difference
time.sleep(2)
print(math.factorial(num))

# calling the function.


factorial(5)

120
Total time taken in : factorial 2.002089738845825

Is lambda a higher-order function in Python?


No, lambda functions are not higher-order functions. They are used to create anonymous
functions. However, they can be used as arguments in higher-order functions.

Why is lambda faster in Python?

lambda functions are slightly faster due to their simple, one-line


syntax and lack of a formal function de�nition overhead.
However, this performance gain is usually marginal.

 What is the highest function in Python?

The concept of functions as �rst-class objects means there is no


single “highest” function. Functions can be passed around,
returned from other functions, and assigned to variables.

Double-click (or enter) to edit

What is the difference between a regular function and a


higher-order function?

12 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...

A regular function performs operations, while a higher-order


function can accept other functions as arguments or return them,
enabling functional programming techniques.

How do higher-order functions relate to functional



programming?

Higher-order functions are fundamental in functional


programming. They allow functions to be used as arguments or
return values, enabling more abstract and functional code.

Start coding or generate with AI.

13 of 13 7/24/24, 14:57

You might also like