What is the output of the following Python code?
Fujitsu technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What is the output of the following Python code? OO®O®@OOOY fg @® @ oonro3sminsesec G)+ What is the output of the following Python code? def func(x): return x * 2 result = list(map(fune, [1, 2, 3, 4])) print(result) AP - A) [1,4,9,16] - B) [2,4,6, 8] - C) [2, 2, 2,2] - D) 112,3, 4]
Show answer & explanation
Answer: B. [2,4,6, 8]
The map function applies the given function 'func' to every element of the provided list. Since 'func' multiplies each input by 2, the resulting list contains the doubles of 1, 2, 3, and 4.
Step-by-step Derivation:
Step 1: Analyze the function definition: def func(x): return x * 2. This function takes an input x and returns its double.
Step 2: Analyze the map call: map(func, [1, 2, 3, 4]). The map function applies func to each element of the iterable [1, 2, 3, 4] sequentially.
Step 3: Perform the calculations:
- For x = 1: 1 * 2 = 2
- For x = 2: 2 * 2 = 4
- For x = 3: 3 * 2 = 6
- For x = 4: 4 * 2 = 8
Step 4: Thelist()constructor converts the map object into a list:[2, 4, 6, 8].
Step 5: Theprint(result)statement outputs the final list.