[Introduction to Python] Lambda Expressions
Lambda expression is an anonymous function that returns some formatted data
The lambda expression syntax is as follows:
lambda parameters: expressions
i.e.
double = lambda num : num * 2
concat_first_letter = lambda a, b, c: a[0] + b[0] + c[0]
concat_first_letter("World", "Wide", "Web")
=>WWW
Lambda expressions must be written on one line, so they are more suitable for shorter functions that can be written on one line.
If you use conditional logic in a lambda expression, you must use the complete one if-else
, and using it alone if
will cause an error:
func = lambda num: "natural number" if num >= 0 else "negative number"
func(0) # 'natural number'
my_func = lambda num: "natural number" if num >= 0 # SyntaxError: invalid syntax
The advantage of using lambda expressions is that you can pass a function as a parameter to another function.
Lambda expression as parameter
Taking addition and multiplication as an example, the writing method using non-lambda is:
def add(n1, n2):
return n1 + n2
def multiply(n1, n2):
return n1 * n2
def calculator(operation, n1, n2):
return operation(n1, n2)
calculator(multiply, 10, 20) # 200
calculator(add, 10, 20) # 30
The lambda expression is written as:
def calculator(operation, n1, n2):
return operation(n1, n2) # Using the 'operation' argument as a function
calculator(lambda n1, n2: n1 * n2, 10, 20) # 200
calculator(lambda n1, n2: n1 + n2, 10, 20) # 30
The same result will be more concise using lambda expressions, which is also the original intention of lambda expressions.
From the official Python documentation - Why can't lambda expressions contain statements? :
Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.
Lambdas in Python are designed to be lazy.
Application of lambda expressions to lists:
num_list = [0, 1, 2, 3, 4, 5]
list(map(lambda n: n ** 2, num_list)) # [0, 1, 4, 9, 16, 25]
list(filter(lambda n: n > 0, num_list)) # [1, 2, 3, 4, 5]