PCEP-30-02 · Question #19
What is the expected output of the following code? ``python 1 nums = [1, 2, 3] 2 data = ('Peter', ) * (len(nums) - nums[::-1][0]) 3 print(data) ``
The correct answer is E. (). Option E is correct because nums[::-1] reverses the list to [3, 2, 1], making nums[::-1][0] equal to 3. Subtracting this from len(nums) (also 3) gives 3 - 3 = 0, so ('Peter',) 0 evaluates to an empty tuple (). Why each distractor fails: A (('Peter', 'Peter')) requires a…
Question
1 nums = [1, 2, 3]
2 data = ('Peter', ) * (len(nums) - nums[::-1][0])
3 print(data)
Options
- A('Peter', 'Peter')
- BPeterPeter
- CThe code is erroneous.
- D('Peter')
- E()
How the community answered
(25 responses)- A12% (3)
- C4% (1)
- D8% (2)
- E76% (19)
Explanation
Option E is correct because nums[::-1] reverses the list to [3, 2, 1], making nums[::-1][0] equal to 3. Subtracting this from len(nums) (also 3) gives 3 - 3 = 0, so ('Peter',) * 0 evaluates to an empty tuple ().
Why each distractor fails:
- A (
('Peter', 'Peter')) requires a multiplier of 2, not 0. - B (
PeterPeter) is impossible - multiplying a tuple never produces a bare string output. - C (erroneous) is wrong - the code runs without error; Python happily multiplies a tuple by 0.
- D (
('Peter')) would require a multiplier of 1, and('Peter')is actually just the string'Peter'anyway - a single-element tuple needs the trailing comma:('Peter',).
Memory tip: When you see a tuple multiplied by an expression, evaluate the expression first - if it resolves to 0, the result is always (), regardless of what's inside the tuple.
Community Discussion
No community discussion yet for this question.