Home>Article> What are the higher-order functions in Python?

What are the higher-order functions in Python?

小老鼠
小老鼠 Original
2023-11-10 16:42:14 1170browse

Higher-order functions include map(), filter(), reduce(), lambda function, partial(), etc. Detailed introduction: 1. map(): This built-in function accepts a function and one or more iterable objects as input, and then returns an iterator that applies the input function to each element of the iterable object; 2. filter() : This built-in function takes a function and an iterable object as input, and returns an iterator that produces those elements that cause the input function to return True, etc.

What are the higher-order functions in Python?

Higher-order functions in Python usually refer to functions that accept one or more functions as input (parameters) or return a function as output. This concept often appears in functional programming.

Here are some examples of higher-order functions in Python:

map(): This built-in function accepts a function and one or more iterable objects as input, and returns a function that An iterator applied to each element of the iterable object.

def square(n): return n * n numbers = [1, 2, 3, 4, 5] squared = map(square, numbers) print(list(squared)) # Output: [1, 4, 9, 16, 25]

filter(): This built-in function accepts a function and an iterable object as input, and returns an iterator that produces those elements that cause the input function to return True.

def is_even(n): return n % 2 == 0 numbers = [1, 2, 3, 4, 5] even_numbers = filter(is_even, numbers) print(list(even_numbers)) # Output: [2, 4]

reduce(): This built-in function accepts a function and an iterable object as input, and then uses the function to combine the elements in the iterable object two by two until only one element remains.

from functools import reduce def add(x, y): return x + y numbers = [1, 2, 3, 4, 5] sum_of_numbers = reduce(add, numbers) print(sum_of_numbers) # Output: 15

lambda function: The lambda function is a way to create anonymous functions, which is very suitable for short function definitions.

squared = list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) print(squared) # Output: [1, 4, 9, 16, 25]

partial(): This function from the functools module is used to partially apply function parameters.

from functools import partial def add(x, y): return x + y add_five = partial(add, 5) # Create a function that adds 5 to its argument. print(add_five(3)) # Output: 8

The above is the detailed content of What are the higher-order functions in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn