Use lambda expressions. Pass a lambda expressions to another method.
Lambda. Think of a tree. Each branch and leaf grows in a pattern. Suppose a tiny function (and many similar functions) constructed this tree.
In Python we have higher-order procedures and the lambda keyword. We pass lambdas to other functions. Much like a tree grows we build a program in little parts.
First example. Lambda expression syntax uses the lambda keyword. The arguments are specified after. A lambda is an object: we can pass it to a def that receives arguments.
Part 1: Here 2 lambdas are created. The first is called "square" and it receives one argument "n" and returns "n * n".
Part 2: We pass the lambdas as an argument to our apply() function. Our lambda expressions are objects.
Part 3: In apply, we call the lambda argument like a function. The logic in the lambda expressions is executed.
Python program that uses lambda argumentdef apply(f, n):
# Part 3: invoke the lambda.
result = f(n)
# Part 1: create 2 similar lambdas.
square = lambda n: n * n
cube = lambda n: n * n * n
# Part 2: pass lambdas to apply method.
Lambda usage. Here we define a lambda that receives no arguments. It simply returns an expression. Here it returns the sum of the numbers 1, 2 and 3 (which is 6).
Variable: We can assign a variable to a lambda expression and then invoke the lambda with parentheses. We call it like any other function.
Here: To get the value 6 in this program, we invoke x. We then print the value it returns (stored in y).
So: Lambdas can be passed to other methods. They can be stored in variables. And those variables can be called like methods.
Python program that uses lambda, no arguments# Assign variable to lambda expression.
x = lambda: sum(range(1, 4))
# Invoke lambda expression.
y = x()
None. Many statements, like print(), return None. This is a valid return value for a lambda. We can specify a lambda with side effects, and a None return value.NonePrint
Python program that uses None, lambda# This lambda has a side effect.
# ... Print returns None.
p = lambda x: print(x)
Nested. A lambda can call another. This can simplify complex computations—we assign names to parts of a computation. The order the lambdas appear in the file does not matter.
With nested lambdas: Recursion can occur. This may result in a RuntimeError: maximum recursion depth exceeded error.
Python program that uses lambda in lambdaadd_two = lambda n: n + 2
multiply_add_two = lambda n: add_two(n * 2) # Call lambda in lambda.
Macros. In older languages like C a macro is an easy way to combine code statements. It reduces repetitive typing. A lambda can be used in this way.
Here: We use a lambda X to combine two string method calls. This is like a macro for those invocations. Typing is reduced.
Python program that uses lambda as macro
line1 = "A cat, a dog "
line2 = " a bird, a mountain"
# Use X as an alias for two methods.
x = lambda s: s.strip().upper()
# Call the lambda to shorten the program's source.
line1b = x(line1)
line2b = x(line2)
A CAT, A DOG
A BIRD, A MOUNTAIN
Avoiding lambda. Sometimes developers use a lambda with one argument and one result, but the lambda is not needed. Here we can use a function name (like math.sqrt) instead of a lambda.
And: When we avoid the lambda, the code becomes clearer and shorter. The lambda does not add much in this case.
Note: Sometimes a program can benefit from lambda when the lambda increases the "symmetry" of the program—other places also use lambda.
Python program that avoids lambda when possible
values = [10, 20, 30]
# Apply sqrt to all elements in the list with map.
result1 = map(math.sqrt, values)
# We can use a lambda, but it is not needed.
result2 = map(lambda x: math.sqrt(x), values)
values: [10, 20, 30]
math.sqrt: [3.1622776601683795, 4.47213595499958, 5.477225575051661]
lambda: [3.1622776601683795, 4.47213595499958, 5.477225575051661]
Lambda, benchmark. Here we test lambda performance. The square() method is rewritten in the def method syntax. We then benchmark the methods against each other.
Version 1: The program tests the performance of the def method call. We call it ten million times.
Version 2: The program times the lambda expression method call. We also call it ten million times.
Result: We find that methods written with the def keyword and with the lambda keyword are close in performance.
Python program that times lambda expressions
return n ** 2
# Lambda method.
square2 = lambda n: n ** 2
# Version 1: use def method.
i = 0
while i < 10000000:
i += 1
# Version 2: use lambda method.
i = 0
while i < 10000000:
i += 1
1346613158.919 (Def = 4.52 s)
1346613163.397 (Lambda = 4.48 s)
Limitations. The lambda syntax in Python has serious limitations. But these limitations make sense. You cannot have multiple statements in a lambda expression.
Tip: If you want many statements, please instead use a def. For complex or involved methods, def is a better option.