What is the output of the following?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the output of the following?**
elements = [0, 1, 2]
def incr(x):
return x+1
print(list(map(incr, elements)))
Pick ONE option
Show answer & explanation
Answer: A. [1, 2, 3]
The map() function applies the incr function to each element in the elements list. For each value (0, 1, 2), incr returns that value plus 1, resulting in (1, 2, 3). The list() constructor converts the map object to a list, and print() outputs it.
Step-by-step Derivation:
Execution trace:
- elements = [0, 1, 2]
- incr(0) = 0 + 1 = 1
- incr(1) = 1 + 1 = 2
- incr(2) = 2 + 1 = 3
- map(incr, elements) returns an iterator over [1, 2, 3]
- list(...) converts it to a list: [1, 2, 3]
- print() outputs: [1, 2, 3]