Lesson 12 of 30
Lambda Functions and Higher-Order Functions
Anonymous functions, map(), filter(), sorted(), and functional programming basics.
Lambda Functions
A lambda is an anonymous single-expression function. Useful for short, throwaway operations:
square = lambda x: x ** 2
print(square(6)) # 36
add = lambda a, b: a + b
print(add(3, 5)) # 8
map()
Apply a function to every item in an iterable:
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16, 25]
filter()
Keep only items for which the function returns True:
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
sorted() with a Key
words = ["banana", "apple", "cherry", "kiwi"]
# sort by length
by_len = sorted(words, key=lambda w: len(w))
print(by_len) # ['kiwi', 'apple', 'banana', 'cherry']
reduce() from functools
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
print(product) # 120