Lambda functions
A lambda is a small anonymous function written in a single expression. It is handy when you need a function for a moment, usually to pass into another function like sorted or map.
Syntax
square = lambda x: x * x
print(square(6))lambda is followed by parameters, a colon and one expression. The expression's value is returned automatically. There is no return keyword and no multi line body.
The same thing with def:
def square(x):
return x * x
print(square(6))If you are going to assign a lambda to a name, use def instead. Lambdas are for the cases below, where the function is used in place.
Multiple parameters
add = lambda a, b: a + b
print(add(2, 3))As a sort key
This is the most common use.
people = [("Zara", 31), ("Amit", 25), ("Neel", 28)]
print(sorted(people, key=lambda p: p[1]))
print(max(people, key=lambda p: p[1]))With map and filter
map applies a function to each item; filter keeps the items where the function returns true.
nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * 10, nums)))
print(list(filter(lambda n: n % 2 == 0, nums)))Comprehensions usually read better for these two:
nums = [1, 2, 3, 4, 5, 6]
print([n * 10 for n in nums])
print([n for n in nums if n % 2 == 0])Returning a lambda from a function
A function can build and return a customised function.
def multiplier(factor):
return lambda x: x * factor
double = multiplier(2)
triple = multiplier(3)
print(double(7), triple(7))Conditional expression inside a lambda
label = lambda n: "even" if n % 2 == 0 else "odd"
print(label(4), label(9))When not to use lambda
- If it needs more than one expression, it is a
def. - If it needs a docstring or a meaningful name, it is a
def. - If you find yourself writing
lambda x: str(x), just passstr.
Practice
- Sort
["banana", "fig", "apple", "kiwi"]by word length using a lambda. - Use
filterwith a lambda to keep only the names that start with "A" in a list. - Write
make_adder(n)that returns a lambda which addsnto its argument.
