Lambda expression is also known as an anonymous function, which means that we don't give a function name.
We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument for a higher-order function. Lambda functions are used along with built-in functions like filter() , map() etc.
The value computed by lambda expression will be returned automatically.
# lambda expression
result = (lambda x: x**2)(5) # 匿名function 自帶return 效果/可輸入input
print(result)
# lambda expression多變數輸入
result_2 = (lambda x, y: (x+y, x-y))(x=5, y=6)
print(result_2)
--------------------------------------------------------------------
25
(11, -1)
# higher order function by map / filter function
for item in map(lambda x: x**2, [5, 10, 15, 20]): # 做原function 的疊加 ,次方 + list input
print(item)
for item in filter(lambda x: x % 2 == 0, [5, 10, 15, 20]): # 做判斷值是否為偶數
print(item)
--------------------------------
#map
25
100
225
400
#filter return
10
20
refer from below
Lambda函式,也就是匿名函式,不需要定義名稱,只有一行運算式,語法非常簡潔,功能強大,所以現代程式語言如Java、C#及Python等都支援Lambda函式,適用於小型的運算,Python的一些內建函式甚至使用它作為參數值的運算。
lambda關鍵字
parameter_list(參數清單)
expression(運算式)