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
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.
Run this code in the editorsquare(4)returns 16 andsquare(2)returns 4, so the sum is 20. 36 would come from squaring the sum (4 + 2) instead of adding the two squares.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
Run this code in the editormap(int, nums)callsinton each string in order, giving the numbers 3, 1 and 2;mapnever sorts.sumadds the numbers to 6. Joining the strings would give "312", but the list already holds ints.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
Run this code in the editorfilterkeeps the items for which the function returns True, in their original order. A list of True and False values is whatmapwould give with the same lambda.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
Run this code in the editorkey=lenmakessortedcompare the lengths (6, 4, 5 and 3) but return the original words, shortest first. Without a key the words would be sorted alphabetically.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
Run this code in the editorreverse=Truekeeps 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.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
Run this code in the editorlist()uses up all the values, so the second finds nothing left and gives an empty list. Storelist(map(...))in a variable to use the results twice.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
Run this code in the editorreducecombines 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.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
Run this code in the editoranyis True when at least one item is truthy, andallis False here because 0 is falsy. For an empty list,allis True (no item fails) andanyis False (no item passes), which surprises many people.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
Run this code in the editormake_multipliercreates a newmultiplyfunction that remembers its ownn. This is a closure:doublekeeps n = 2 andtriplekeeps n = 3, even aftermake_multiplierhas returned. The second call does not change the first function.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
Run this code in the editori; they look it up when they are called. By then the loop has finished andiis 2, so every call returns 20. Writinglambda i=i: i * 10captures the current value and gives [0, 10, 20].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
Run this code in the editor@twicereplacesadd_threewithwrapper, 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.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
Run this code in the editordefstatement is executed, not each time the function is called.announceprints its message at that moment and returns the original function unchanged, so the two calls print only "hello".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.
Run this code in the editorreturnis a statement, so it is not allowed there, and Python reports a SyntaxError before running anything. Writelambda x: x * 2.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
Run this code in the editorfilterkeeps nothing andexpensiveis an empty list.max()of an empty sequence has no answer and raises ValueError;max(expensive, default=0)would return 0 instead.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
Run this code in the editor@logmeansgreet = log(greet).logdefineswrapperbut never returns it, so it returns None andgreetbecomes None. Callinggreet()then calls None, which raises TypeError. Addingreturn wrapperat the end oflogfixes it.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,
mapandfilterare lazy: they return iterator objects and compute each result only when asked. Wrap the call inlist()to get ['1', '2', '3']. Older books saymapreturns a list because it did in Python 2.Question 17 · Easy
Which statement about
lambdais 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
returnor assignments are not allowed. Lambdas can have defaults, as inlambda x, y=2: x * y, and can be called without a name, as in(lambda: 5)().Question 18 · Medium
For a function
fof two arguments, what doesreduce(f, [a, b, c])fromfunctoolscompute?Show the answer
Answer: A, f(f(a, b), c)
reduceworks 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 offapplied to each item is whatmapgives.Question 19 · Medium
With
nums = [1, 2, 3, 4, 5, 6], which expression gives[4, 16, 36]?Show the answer
Answer: D
filterfirst keeps the even numbers 2, 4 and 6, thenmapsquares 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.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
keymust be a function thatsortedcalls on each item;lambda p: p[1]picks the age.keyis keyword-only, so passing the lambda by position raises TypeError, andpeople[1]is a tuple, not a function. Sorting onp[0]orders by name.
Keep going
- Read the lesson behind these questions: Lambda, map and filter in the PythonBook
- Next topic: Python exception handling MCQ questions with answers
- Before this: Python functions MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.