Python programs often use the lambda keyword. Methods like map()
can receive a lambda to specify their behavior. In this way we can specify behavior as arguments.
We cannot have multiple statements in a lambda expression. If we require many statements in a complex method, consider a def.
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.
apply()
function. Our lambda expressions are objects.def apply(f, n): # Part 3: invoke the lambda. result = f(n) print("RESULT:", result) # Part 1: create 2 similar lambdas. square = lambda n: n * n cube = lambda n: n * n * n # Part 2: pass lambdas to apply method. apply(square, 4) apply(cube, 3)RESULT: 16 RESULT: 27
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).
# Assign variable to lambda expression. x = lambda: sum(range(1, 4)) # Invoke lambda expression. y = x() print(y)6
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.
# This lambda has a side effect. # ... Print returns None. p = lambda x: print(x) p("Hello") p("World")Hello World
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.
RuntimeError
: maximum recursion depth exceeded error.add_two = lambda n: n + 2 multiply_add_two = lambda n: add_two(n * 2) # Call lambda in lambda. print(multiply_add_two(3)) print(multiply_add_two(5))8 12
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.
string
method calls. This is like a macro for those invocations. Typing is reduced.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) print(line1b) print(line2b)A CAT, A DOG A BIRD, A MOUNTAIN
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.
import math 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) print("values:", values) print("math.sqrt:", list(result1)) print("lambda:", list(result2))values: [10, 20, 30] math.sqrt: [3.1622776601683795, 4.47213595499958, 5.477225575051661] lambda: [3.1622776601683795, 4.47213595499958, 5.477225575051661]
Here we test lambda performance. The square()
method is rewritten in the def method syntax. We then benchmark the methods against each other.
import time # Method. def square1(n): return n ** 2 # Lambda method. square2 = lambda n: n ** 2 print(time.time()) # Version 1: use def method. i = 0 while i < 10000000: square1(1) i += 1 print(time.time()) # Version 2: use lambda method. i = 0 while i < 10000000: square2(1) i += 1 print(time.time())1346613154.399 1346613158.919 (Def = 4.52 s) 1346613163.397 (Lambda = 4.48 s)
Function objects provide many possibilities. We specify these objects with the lambda syntax form. And when we pass them to other functions, we develop higher-order procedures.