# Kết quả: 20
# By TipsMake.com
print(nhan_doi(10))
In this example, lambda a: a * 2
is Lambda function. a
here is the parameter and a * 2
is the expression (taking into account the calculation and returning the result). This function has no name, it returns a function object - assigned a nhan_doi.
We can call it as a normal function, the following command:
nhan_doi = lambda a: a * 2
almost like:
def nhan_doi(a):
return a * 2
Usually Lambda function is used when an anonymous function is needed in a short time, for example as an argument to a higher order function. Lambda function is often used with built-in Python functions such as filter () or map (), .
For example, using Lambda function with filter ():
The filter () function takes parameters as a function and a list. The function is called with all the items in the list and the new list will be returned, containing the items that the function evaluates to as True. This is an example of using the filter () function to filter out even numbers in the list.
list_goc = [10, 9, 8, 7, 6, 1, 2, 3, 4, 5]
list_moi = list(filter(lambda a: (a%2 == 0) , list_goc))
# Kết quả: [10, 8, 6, 2, 4]
# By TipsMake.com
print(list_moi)
For example, using Lambda function with map ():
The map () function also takes parameters as a function and a list. The function is called with all the items in the new list and list returned containing the items returned by the corresponding function for each item. Saying it seems ambiguous, you see the following example will be much easier to understand:
list_goc = [10, 9, 8, 7, 6, 1, 2, 3, 4, 5]
list_moi = list(map(lambda a: a*2 , list_goc))
# Kết quả: [20, 18, 16, 14, 12, 2, 4, 6, 8, 10]
# By TipsMake.com
print(list_moi)
Is there anything in the anonymous function that we missed? Please comment below to comment. Don't forget to do Python exercises and look forward to the next lesson.
Next lesson: Global variable (global), local variable (local), nonlocal variable in Python
Previous lesson: Python recursive function