

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Functions As Values
incomplete
2: Anonymous Functions
incomplete
3: First-Class and Higher-Order Functions
incomplete
4: Map
incomplete
5: Filter
incomplete
6: Reduce
incomplete
7: Map, Filter, and Reduce Review
incomplete
8: Zip
incomplete
9: Higher-Order Functions Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Anonymous functions have no name, and in Python, they're called lambda functions after lambda calculus. Here's a lambda function that takes a single argument x and returns the result of x + 1:
lambda x: x + 1
Notice that the expression x + 1 is returned automatically, no need for a return statement. Compare that to how you'd normally write a function:
def add_one(x: int) -> int:
return x + 1
Because functions are just values, we can assign the function to a variable named add_one:
from collections.abc import Callable
add_one: Callable[[int], int] = lambda x: x + 1
print(add_one(2))
# 3
Lambda functions might look scary, but they're still just functions. Because they simply return the result of an expression, they're often used for small, simple evaluations. Here's an example that uses a lambda to get a value from a dictionary:
get_age: Callable[[str], int | str] = lambda name: {
"lane": 29,
"hunter": 69,
"allan": 17,
}.get(name, "not found")
print(get_age("lane"))
# 29
Complete the file_type_getter function. This function accepts a list of tuples, where each tuple contains:
"code", "document", "image", etc.)[".py", ".js"] or [".docx", ".doc"])The function returns a function for looking up the file type of a given file extension.
For example, if given the following list of tuples:
# list of tuples
file_extension_tuples: list[tuple[str, list[str]]] = [
("document", [".doc", ".docx"]),
("image", [".jpg", ".png"]),
]
# resulting dictionary
file_extensions_dict: dict[str, str] = {
".doc": "document",
".docx": "document",
".jpg": "image",
".png": "image",
}