Higher-Order functions in Python
They are simpler, less time-consuming and clean.
Higher-Order functions
These are the functions that is having another function as an argument or a function that returns another function as a return in the output.
Examples of Higher-Order functions are : map(), filter(), reduce()
Before looking further into these functions, let's see something known as Lambda Function.
LAMBDA FUNCTION:
This function can have any number of arguments but only one expression, which is evaluated and returned.
The lambda function is usually used with higher-order functions.
1. map()
Map is a function that works like list comprehensions and for loops. It is used when you need to map or implement functions on various elements at the same time.
SYNTAX:
map(function, iterable object)
Let's see an example.
list_numbers = (1,2,3,4)
sample_map = map(lambda x: x*2, list_numbers)
print(list(sample_map))
The output we get is [2, 4, 6, 8]
.
2. filter()
Filter is a similar operation, but it requires the function to look for a condition and then returns only those elements that satisfy the condition, from the collection.
SYNTAX:
filter(function, iterable object)
The following code prints the names that only start with an 'A'.
name = ['Harshit','Aman','Mohith','Akash']
sample_name = filter(lambda x : x.startswith("A"), name)
print(list(sample_name))
This prints the following output ['Aman', 'Akash']
.
3. reduce()
Reduce is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.
SYNTAX:
reduce(function, iterable object)
Note: the reduce function needs to be imported from the 'functools' library.
from functools import reduce
list_1 = [7,8,4,6,3]
result = reduce(lambda x,y: x+y ,list_1)
print(result)
The result printed is 28
which is the cumulative sum of the list.
Hope this article was helpful. For further digging, take a look here.
Do share your thoughts in the comment section below. You can reach out to me on Linkedin as well. Happy learning!!