Small, nameless, one-expression functions, written right where you need them.
# lambda syntax
square = lambda x: x ** 2
result = square(5)
# ans: 25
lambda replaces def and the name.
Parameters come before the colon, without brackets.
The body is one expression, and its value is returned automatically: no return.
# multiple parameters
add = lambda x, y: x + y
result = add(3, 4)
# ans: 7
# lambda as key function
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[1])
# ans: [(1, 'one'), (3, 'three'), (2, 'two')]
# lambda with map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# ans: [1, 4, 9, 16, 25]
map calls the lambda on every item.
# lambda with filter
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# ans: [2, 4]
filter keeps the items for which the lambda returns True.
Predict the result, then press → to check.
# what is result?
f = lambda x: x * 2
f(5)
# ans: 10
# lambda with two parameters?
multiply = lambda a, b: a * b
multiply(3, 4)
# ans: 12
# immediate invocation?
(lambda x: x + 1)(5)
# ans: 6
# lambda vs def?
f = lambda x: x ** 2
def g(x):
return x ** 2
f(3) == g(3)
# ans: True
# lambda with conditional?
abs_val = lambda x: x if x >= 0 else -x
abs_val(-5)
# ans: 5
# can lambda have multiple lines?
f = lambda x: x + 1
x + 2
# ans: SyntaxError (a lambda is a single expression)
# lambda in list?
funcs = [lambda x: x+1, lambda x: x*2]
funcs[0](5)
# ans: 6
# lambda with default argument?
f = lambda x=5: x * 2
f()
# ans: 10
# nested lambda?
f = lambda x: (lambda y: x + y)
f(5)(3)
# ans: 8
f(5) returns lambda y: 5 + y, which is then called with 3.
# lambda without parameter?
f = lambda: 42
f()
# ans: 42
lambda params: expression, with the value returned automatically.
No statements, no multiple lines; use def for anything bigger.
Short keys and tests for sorted, map and filter.