Anonymous Functions
Last updated
Last updated
Anonymous functions have no name, and in Python, they're called after . Here's a lambda function that takes a single argument x
and returns the result of x + 1
:
Notice that the x + 1
is returned automatically, no need for a return
statement. And because functions are just values, we can assign the function to a variable named add_one
:
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:
Complete the file_type_getter
function. This function accepts a list of tuples, where each tuple contains:
A "file type" (e.g. "code", "document", "image", etc)
A list of associated file extensions (e.g. [".py", ".js"]
or [".docx", ".doc"]
)
First, use loops to create a dictionary that maps each file extension to its corresponding file type, based on the input tuples. For example, the resulting dictionary might be:
Next, return a lambda function that accepts a string (a file extension) and returns the corresponding file type. If the extension is not found in the dictionary, the lambda function should return "Unknown"
. I used the dictionary method to handle this.