Editor

Python lambda, map and filter MCQ questions with answers

lambda, map, filter, sorted keys and closures, one question at a time.

0 of 20 answered

  1. Question 1 · Easy

    What is the output of this code?

    square = lambda x: x * x
    print(square(4) + square(2))
    Show the answer

    Answer: B

    A lambda is a small unnamed function. square(4) returns 16 and square(2) returns 4, so the sum is 20. 36 would come from squaring the sum (4 + 2) instead of adding the two squares.

    Run this code in the editor
  2. Question 2 · Easy

    What is the output of this code?

    nums = ["3", "1", "2"]
    result = list(map(int, nums))
    print(result, sum(result))
    Show the answer

    Answer: D

    map(int, nums) calls int on each string in order, giving the numbers 3, 1 and 2; map never sorts. sum adds the numbers to 6. Joining the strings would give "312", but the list already holds ints.

    Run this code in the editor
  3. Question 3 · Easy

    What is the output of this code?

    marks = [45, 82, 30, 67, 91]
    passed = list(filter(lambda m: m >= 50, marks))
    print(passed)
    Show the answer

    Answer: A

    filter keeps the items for which the function returns True, in their original order. A list of True and False values is what map would give with the same lambda.

    Run this code in the editor
  4. Question 4 · Easy

    What is the output of this code?

    words = ["banana", "kiwi", "apple", "fig"]
    print(sorted(words, key=len))
    Show the answer

    Answer: C

    key=len makes sorted compare the lengths (6, 4, 5 and 3) but return the original words, shortest first. Without a key the words would be sorted alphabetically.

    Run this code in the editor
  5. Question 5 · Hard

    What is the output of this code?

    students = [("Asha", 82), ("Ravi", 95), ("Meera", 82)]
    ranked = sorted(students, key=lambda s: s[1], reverse=True)
    print([name for name, mark in ranked])
    Show the answer

    Answer: C

    Python's sort is stable: items with equal keys keep their original order, and reverse=True keeps that rule. Ravi (95) comes first, then the two 82s in the order they appeared, Asha before Meera. Reversing an ascending sort afterwards would put Meera first.

    Run this code in the editor
  6. Question 6 · Medium

    What is the output of this code?

    doubled = map(lambda n: n * 2, [1, 2, 3])
    print(list(doubled))
    print(list(doubled))
    Show the answer

    Answer: A

    A map object is an iterator: it produces each value once. The first list() uses up all the values, so the second finds nothing left and gives an empty list. Store list(map(...)) in a variable to use the results twice.

    Run this code in the editor
  7. Question 7 · Medium

    What is the output of this code?

    from functools import reduce
    
    nums = [1, 2, 3, 4]
    print(reduce(lambda a, b: a * b, nums))
    print(reduce(lambda a, b: a + b, nums, 10))
    Show the answer

    Answer: D

    reduce combines the items pairwise from the left, ((1 * 2) * 3) * 4 = 24, and returns one value, not a list of steps. The third argument is a starting value, so the second call computes 10 + 1 + 2 + 3 + 4 = 20 rather than 10.

    Run this code in the editor
  8. Question 8 · Medium

    What is the output of this code?

    scores = [0, 3, 5]
    print(any(scores), all(scores))
    print(all([]), any([]))
    Show the answer

    Answer: B

    any is True when at least one item is truthy, and all is False here because 0 is falsy. For an empty list, all is True (no item fails) and any is False (no item passes), which surprises many people.

    Run this code in the editor
  9. Question 9 · Medium

    What is the output of this code?

    def make_multiplier(n):
        def multiply(x):
            return x * n
        return multiply
    
    double = make_multiplier(2)
    triple = make_multiplier(3)
    print(double(5), triple(5))
    Show the answer

    Answer: A

    Each call to make_multiplier creates a new multiply function that remembers its own n. This is a closure: double keeps n = 2 and triple keeps n = 3, even after make_multiplier has returned. The second call does not change the first function.

    Run this code in the editor
  10. Question 10 · Hard

    What is the output of this code?

    funcs = []
    for i in range(3):
        funcs.append(lambda: i * 10)
    
    print([f() for f in funcs])
    Show the answer

    Answer: B

    The lambdas do not store the value of i; they look it up when they are called. By then the loop has finished and i is 2, so every call returns 20. Writing lambda i=i: i * 10 captures the current value and gives [0, 10, 20].

    Run this code in the editor
  11. Question 11 · Medium

    What is the output of this code?

    def twice(func):
        def wrapper(x):
            return func(func(x))
        return wrapper
    
    @twice
    def add_three(n):
        return n + 3
    
    print(add_three(10))
    Show the answer

    Answer: C

    @twice replaces add_three with wrapper, which calls the original function on its own result: add_three(add_three(10)) = add_three(13) = 16. 13 is what the function would return without the decorator.

    Run this code in the editor
  12. Question 12 · Hard

    What is the output of this code?

    def announce(func):
        print("decorating", func.__name__)
        return func
    
    @announce
    def hello():
        print("hello")
    
    hello()
    hello()
    Show the answer

    Answer: D

    A decorator runs once, when the def statement is executed, not each time the function is called. announce prints its message at that moment and returns the original function unchanged, so the two calls print only "hello".

    Run this code in the editor
  13. Question 13 · Easy

    Which error does this code raise?

    double = lambda x: return x * 2
    print(double(4))
    Show the answer

    Answer: D, SyntaxError: invalid syntax

    A lambda body must be a single expression, and its value is returned automatically. return is a statement, so it is not allowed there, and Python reports a SyntaxError before running anything. Write lambda x: x * 2.

    Run this code in the editor
  14. Question 14 · Medium

    Which error does this code raise?

    prices = [120, 80, 95]
    expensive = list(filter(lambda p: p > 150, prices))
    print(max(expensive))
    Show the answer

    Answer: C, ValueError: max() iterable argument is empty

    No price is above 150, so filter keeps nothing and expensive is an empty list. max() of an empty sequence has no answer and raises ValueError; max(expensive, default=0) would return 0 instead.

    Run this code in the editor
  15. Question 15 · Hard

    What happens when this code runs?

    def log(func):
        def wrapper():
            print("calling", func.__name__)
            return func()
    
    @log
    def greet():
        return "hi"
    
    print(greet())
    Show the answer

    Answer: B, TypeError: 'NoneType' object is not callable

    @log means greet = log(greet). log defines wrapper but never returns it, so it returns None and greet becomes None. Calling greet() then calls None, which raises TypeError. Adding return wrapper at the end of log fixes it.

    Run this code in the editor
  16. Question 16 · Easy

    What does map(str, [1, 2, 3]) return in Python 3?

    Show the answer

    Answer: A, A map object: an iterator that produces the results one at a time

    In Python 3, map and filter are lazy: they return iterator objects and compute each result only when asked. Wrap the call in list() to get ['1', '2', '3']. Older books say map returns a list because it did in Python 2.

  17. Question 17 · Easy

    Which statement about lambda is true?

    Show the answer

    Answer: B, A lambda's body is a single expression, and its value is returned

    A lambda holds exactly one expression, which is evaluated and returned when it is called; statements such as return or assignments are not allowed. Lambdas can have defaults, as in lambda x, y=2: x * y, and can be called without a name, as in (lambda: 5)().

  18. Question 18 · Medium

    For a function f of two arguments, what does reduce(f, [a, b, c]) from functools compute?

    Show the answer

    Answer: A, f(f(a, b), c)

    reduce works from the left: it combines the first two items, then combines that result with the next item, and so on, so the result is f(f(a, b), c). A list of f applied to each item is what map gives.

  19. Question 19 · Medium

    With nums = [1, 2, 3, 4, 5, 6], which expression gives [4, 16, 36]?

    Show the answer

    Answer: D

    filter first keeps the even numbers 2, 4 and 6, then map squares each of them. Filtering alone gives [2, 4, 6], mapping the test alone gives True and False values, and the first option maps to booleans before filtering, so it never squares anything.

  20. Question 20 · Easy

    With people = [("Asha", 17), ("Ravi", 15), ("Meera", 16)], which expression returns the list sorted from youngest to oldest?

    Show the answer

    Answer: C

    key must be a function that sorted calls on each item; lambda p: p[1] picks the age. key is keyword-only, so passing the lambda by position raises TypeError, and people[1] is a tuple, not a function. Sorting on p[0] orders by name.

Keep going