Skip to the content

lambda

Python · Unit 10: More on functions

lambda makes a small function in a single line. Before the colon go the parameters; after it, what it returns, without writing return.

lambda x: x * 2 does the same as a def whose only step is return x * 2.

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

Prints

10

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank to make a function that returns half of a number.

  3. 3. Find the bug

    This program should print 36. Which line has the bug?

  4. 4. Predict the output

    What does this code print?

  5. 5. Complete the code

    Fill in the blank to work out the average of two grades.

  6. 6. Find the bug

    This program should print 8. Which line has the bug?

  7. 7. Predict the output

    What does this code print?

  8. 8. Multiple choice

    What does this code do?

  9. 9. Multiple choice

    Which of these functions is better written with def than with lambda?

  10. 10. Predict the output

    A for over a dictionary gives its keys, and so does sorted. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →