I'll forget about anonymous functions soon, so make a note for myself
Used for code simplification
def calc_multi(a, b):
return a * b
calc_multi(3, 10)
#output
# 30
This process can be written as The point is lambda a, b:, which corresponds to the function name (a, b) Describe the processing of the function (return a * b here) separated by:
(lambda a, b: a * b)(3, 10)
#output
# 30
Lambda expressions are often used when you want to execute some function on an element such as a list Use ** map function (higher-order function) ** when you want to process an element A function that uses a function as an argument or return value, and is used when you want to process or operate on each element.
def calc_double(x) :
return x * 2
for num in [1, 2, 3, 4]:
print(calc_double(num))
#output
# 2
# 4
# 6
# 8
If you use the map function, you can process the list as it is
list(map(calc_double, [1, 2, 3, 4]))
#output
# [2,4,6,8]
Furthermore, if you use an anonymous function, you can write as follows
list(map(lambda x : x * 2, [1, 2, 3, 4]))
#output
# [2,4,6,8]
Recommended Posts