Lambda functions
A small function, written in one expression.
Put a value in. Get a value back.
A function can take an input, apply a rule, and return a result.lambda is a short way to create one.
xlambda x: x * 25 * 2Each change calls the function again with your chosen input.
Read it from left to right.
“Take x, and give back x * 2.”
lambda tells Python to create a function. It doesn’t need a name here.
The input name is a parameter. After the colon comes one expression: code that produces a value. That value is returned automatically, so you don’t write return.
Can it take more than one input?
Yes. Separate the parameters with commas.
lambda x, y: x + yWith x = 2 and y = 3, this function returns 5. The body is still one expression.
Create it. Then call it.
Creating a function saves the rule. Calling it runs the rule.
Here, we name the function double so we can call it.
double = lambda x: x * 2double(5)not called yetdoublea functionThe function is ready. No multiplication has happened yet.
The parentheses in double(5) make the call. The value 5 is the argument passed into the parameter x.
How does this compare with def?
With def
def double(x):
return x * 2With lambda
double = lambda x: x * 2Both return 10 when called with 5. The lambda returns the expression’s value automatically.
We named the lambda to make this example easy to follow. For a function you want to name and reuse, prefer def.
A little rule, right where you need it.
Lambdas are useful when another function needs a short rule. You can put the lambda directly in the call, without naming it first. That’s why it’s called an anonymous function.
See an example: sort words by length
sorted puts items in order. Its key is a function that tells it what to compare. Here, len(word) gives each word’s length.
words = ["pear", "fig", "banana"]
sorted(words, key=lambda word: len(word))
Original order
pear4 lettersfig3 lettersbanana6 letters
The lambda supplies lengths to compare. The result will still contain words.
Keep the expression easy to read. If the function needs several steps, use def.
The pattern to remember
lambda inputs: expressionCreate the function. Call it with values. Get the result.
Which part names the input?
1 of 4Take your time. You can try each answer again.
You’ve got the idea.
A lambda creates a function.
Calling it returns the value of its expression.
lambda x: x * 2
Review the lesson
Continue to Lambdas in practice