Lambda functions

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.

Input5x
Double itlambda x: x * 25 * 2
Result10returned

Each change calls the function again with your chosen input.

Read it from left to right.

“Take x, and give back x * 2.”

Create a function
Name the input
Separate
Give back a value

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 + y

With 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 * 2
double(5)not called yet
doublea function

The 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 * 2

With lambda

double = lambda x: x * 2

Both 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

  1. pear4 letters
  2. fig3 letters
  3. banana6 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: expression

Create the function. Call it with values. Get the result.

Next lesson: Lambdas in practice