13. Lambda
A lambda is a small anonymous function written in a single expression:
parameters— zero or more parameters, separated by commas, like indef.expression— a single expression; its value is returned automatically. There is noreturnand no block of statements.
Lambdas are often passed directly to functions that expect a function, such as sorted(key=...) or map():
sorted(iterable, key=...)orders the elements by the value returned bykey.map(function, iterable)applies the function to each element. Wrap it inlist()to see the results.
Coming from JavaScript? A lambda is an arrow function with an expression body: lambda n: n * 2 is (n) => n * 2. The body must be one expression (no block, no return, no if statement), and a lambda captures the variable, not its value:
Store a lambda in a variable
Assign a lambda to the variable double. It takes one parameter n and returns n * 2. Print double(5).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A lambda with two parameters
Assign a lambda to the variable add. It takes two parameters a and b and returns their sum. Print add(2, 3).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use a lambda as a sort key
Use words = ["bbb", "a", "cc"]. Sort the list with sorted() and pass a lambda as the key argument. The lambda returns the length of a word, so the list is ordered from the shortest word to the longest. Print the sorted list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use a lambda with map
Use numbers = [1, 2, 3]. Use map() with a lambda that squares its argument, wrap the result in list() and print it.
Print exactly:
Create a free account to save your progress and unlock chapter 2.