def hello():
print("Ahoy")
def sum(x, y):
return x + y
type(hello) # <class 'function'>
type(sum) # <class 'function'>
hello() # Ahoy
sum(1, 1) # 2
hello = lambda: print("Ahoy")
sum = lambda x, y: x + y
type(hello) # <class 'function'>
type(sum) # <class 'function'>
hello() # Ahoy
sum(1, 1) # 2
The Lambda function is ideal for map, reduce, filter, and other built-in functions as a conditional function. In the following example, let's take the map function as an example and make all the values in the list 10 times.
def mul_10(x):
return x * 10
li = [1, 2, 3]
li = [*map(mul_10, li)]
# li = [10, 20, 30]
li = [1, 2, 3]
li = [*map(lambda x: x * 10, li)]
# li = [10, 20, 30]
Article | Link |
---|---|
Python進階技巧 (4) — Lambda Function 與 Closure 之謎! | https://medium.com/citycoddee/python進階技巧-4-lambda-function-與-closure-之謎-7a385a35e1d8 |
5 Python tricks that will improve your life [6:34] | https://youtu.be/5tcs2qXP3Pg?t=394 |