Higher order functions in python

Functions that take a function as an argument or return a function are called higher order functions.Functions and methods are first-class objects in Python, so if you want to pass a function to another function, you can just treat it as any other object. Some of the examples of higher order functions are map(), reduce(), filter()

Map function

  • map(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the returned values.
# function to square numbers
defsquare(x):    
return x**2
# map function
mapped = list(map(square, [1,2,3,4,5]))print(mapped)
Output:[1, 4, 9, 16, 25]

Filter Function

  • filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true.
# function to check if number is positive
defpositive(x):    
     return x > 0
# filter function
filtered = list(filter(positive, [-3,-2,-1,1,2,3,4]))
print(filtered)
Output:[1, 2, 3, 4]

Reduce Function

  • reduce(function, sequence) takes an iterable of input data and consumes it to come up with a single value.
# import reduce from functools 
import reduce
# function to divide two numbers
def add(x,y):    
     return x + y
# reduce function
reduced = reduce(add, [1,2,3])print(reduced)
Output: 6

This covers a short introduction to commonly used higher order functions in python. Follow us on Facebook or Instagram to get notified about upcoming short articles in python.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.