Higher-Order Function

what is a Higher-Order Function?
In Python a higher-order function is a function that takes takes one or more function as arguments, return a function as its result or both.
In other words, it treats functions as first-class citizens, allowing them to be manipulated just like any other object such as integers, string or list.
most common Higher-Order Function
map()
filter()
reduce()
map() - Applying a Function to Each Element in an iterable
The map() function takes a function and an iterable (e.g, a list) as input and applies the function to each element in the iterable, returning a new iterable with the result.
def square(x): return x * x number = [1,2,3,4,5,6] squared_number = map(square, number) print(list(squared_number)) # Output: [1,4,9,16,25,36]
filter() - Filtering Elements in an Iterable
The filter() function takes a function and an iterable as input and return a new iterable containing only the elements for which the function return True.
def even(x): return x % 2 == 0 number = [1,2,3,4,5,6] even_number = filter(even, number) print(list(even_number)) # Output: [2,4,6]
reduce() - Aggregating Elements in an Iterable
The reduce() function takes a function and an iterable as input and successively applies the function to the elements, reducing the iterable to a single value.
from functools import reduce def add(x, y): return x + y numbers = [1,2,3,4,5] sum_of_number = reduce(add, numbers) print(sum_of_number) # Output: 15



