Python advanced | talk about several commonly used built-in functions

Python advanced | talk about several commonly used built-in functions

Anonymous function (lambda expression)

In Python, functions can be regarded as "first-class citizens". Let's review the advantages of functions:

  • Reduce the amount of code duplication
  • Modular code

But have we ever thought that if we need a function, which is short, and only needs to be used once (no need to call it repeatedly), do we need to define a named function?

The answer is no, here we can use anonymous functions to achieve such a function.

Let's first look at how to square a number, and how to define a function:

def square(x):
    return x**2

square(3)

The lambda expression can be written like this:

square = lambda x: x**2
square(3)

According to the above example, in fact, the use of lambda expressions is still very simple, as follows:

lambda argument1, argument2,.....: expression

Next, the map, filter, and reduce functions introduced can be used in combination with lambda expressions to play their powerful role.

map function

The use of the map function is as follows:

map(function, iterable)

Its function is to use the function function for each element of iterable, and finally return a new traversable collection.

a = [1,2,3,4,5]
b = map(lambda x: x*2,a)
print(list(b))
# [2, 4, 6, 8, 10]
filter function

The use of the filter function is as follows:

filter(function, iterable)

Its function is to use the function function to judge each element of iterable, and finally return a new traversable set that is all True.

a = [1,2,3,4,5,6]
b = filter(lambda x :x%2 == 0, a)
print(list(b))
# [2, 4, 6]
reduce function

The use of the reduce function is as follows:

reduce(function, iterable)

The function stipulates two parameters, which means that the function operation is performed on each element of the iterable and the result of the previous operation, and finally a value is obtained. Note that we need to import reduce from functools.

from functools import reduce

a = [1,2,3,4]
b = reduce(lambda x,y: x*y,a)
print(b)
# 24 1*2*3*4
summary
  • lambda expression
  • map, filter and reduce functions
Reference: https://cloud.tencent.com/developer/article/1524293 Advanced Python|Talk about a few commonly used built-in functions-Cloud + Community-Tencent Cloud