PCEP-30-02 · Question #36
What is the expected output of the following code? ``python data1 = (1, 2) data2 = (3, 4) [print(sum(x)) for x in [data1 + data2]] ``
The correct answer is B. 10. Option B is correct because data1 + data2 performs tuple concatenation (not element-wise addition), producing (1, 2, 3, 4). Wrapping it in [data1 + data2] creates a one-element list containing that full tuple, so the comprehension iterates exactly once with x = (1, 2, 3, 4)…
Question
data1 = (1, 2)
data2 = (3, 4)
[print(sum(x)) for x in [data1 + data2]]
Options
- A4
- B10
- CNothing gets printed.
- DThe code is erroneous.
How the community answered
(42 responses)- A7% (3)
- B71% (30)
- C17% (7)
- D5% (2)
Explanation
Option B is correct because data1 + data2 performs tuple concatenation (not element-wise addition), producing (1, 2, 3, 4). Wrapping it in [data1 + data2] creates a one-element list containing that full tuple, so the comprehension iterates exactly once with x = (1, 2, 3, 4), and sum((1, 2, 3, 4)) = 10.
A (4) is wrong - a common trap for those who confuse + on tuples with numeric addition or assume element-wise operations; Python's + on sequences always concatenates.
C (Nothing printed) is wrong - list comprehensions still execute side effects like print; the return value of the comprehension is discarded, but the print fires.
D (Erroneous) is wrong - every operation here is valid Python: tuple concatenation, list wrapping, sum() on an iterable, and print inside a comprehension all work without error.
Memory tip: When you see tuple1 + tuple2, always think glue, not math - Python sequences join end-to-end. Count the brackets carefully too: [data1 + data2] is a list of one tuple, not a list of four numbers.
Community Discussion
No community discussion yet for this question.