PSC-UNIT1-3-Higher Order Functions in Python
PSC-UNIT1-3-Higher Order Functions in Python
A function is called
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.
1 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...
Returning function
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
Examples
Map
Reduce
Filter
map
The returned value from map() (map object) then can be passed to functions like list() (to
create a list), set() (to create a set) .
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]
base = [1, 2, 3, 4]
power = [1, 2, 3, 4]
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
def distance(point) :
x, y, z = point
return sqrt(x**2 + y**2 + z**2)
�lter(function, iterable)
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()
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...
nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]
[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]
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"]},
]
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:
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.
Output:720
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))
nums = [1, 2, 3, 4, 5, 6, 7, 8]
print(nums)
Decorators in Python
8 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...
print(shout('Hello'))
yell = shout
print(yell('Hello'))
HELLO
HELLO
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)
9 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...
def create_adder(x):
def adder(y):
return x+y
return adder
add_15 = create_adder(15)
print(add_15(10))
25
# defining a decorator
def hello_decorator(func):
10 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...
return inner1
# importing libraries
import time
import math
func(*args, **kwargs)
return inner1
11 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...
120
Total time taken in : factorial 2.002089738845825
12 of 13 7/24/24, 14:57
Higher Order Functions in Python - Colab https://colab.research.google.com/drive/1WDHTSeDd3LM...
13 of 13 7/24/24, 14:57