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, 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, 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, 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