← All lessons

lambda: a one-line function

Sign in · Sign up

Lesson 6.8

lambda is a short function without def and without return:

double = lambda x: x * 2
print(double(5))   # 10

It reads like this: arguments on the left, the result on the right. Lambdas are often passed to key to sort a list your own way:

sorted(words, key=lambda w: len(w))

Write a function twice(x) with lambda that doubles a number, and save it in the variable twice.

Hint

A lambda is a one-line function: lambda x: x * 2.

After the colon comes an expression, and return is not written. A lambda is handy to pass straight into map or sorted.