Lambda functions

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? add = lambda a, b: a + b print(add(3, 2))

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Lambda functions explained

    A lambda is a small anonymous function written as a single expression. It is useful when a short function is needed only once, such as a sort key or a callback, and it is written with the keyword lambda.

    The syntax is lambda parameters: expression. A lambda returns the value of its expression automatically, so it has no return statement. It can take any number of parameters, but it holds only one expression, so it cannot contain statements such as assignments or loops.

    Lambdas are often passed to functions that accept another function, such as sorted with a key argument, map and filter. A named def is better when the logic is longer than one expression or needs a meaningful name for reuse.

    Assigning a lambda to a name, as in double = lambda x: x * 2, behaves like a def but is less clear. The style guide PEP 8 recommends a def statement in that case.

    Worked example

    words = ["banana", "fig", "kiwi"]
    print(sorted(words, key=lambda w: len(w)))
    print(list(map(lambda x: x * 10, [1, 2, 3])))
    
    1. The key function returns the lengths 6, 3 and 4, so the sorted order is fig (3), kiwi (4), banana (6).
    2. Applying the lambda to 1, 2 and 3 gives 10, 20 and 30.

    Check: the sorted lengths 3, 4 and 6 increase, so the shortest word comes first.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? add = lambda a, b: a + b print(add(8, 1))

    • Medium

      What does this Python code print? nums = [19, 4, 20, 7, 17, 4, 14] print(sorted(nums, key=lambda x: x % 3)[0])

    • Hard

      What does this Python code print? fns = [lambda: i * 3 for i in range(5)] print(fns0)