PCEP-30-02 · Question #33
What is the expected output of the following code? ``python data = {1: 0, 2: 1, 3: 2, 0: 1} x = 0 for _ in range(len(data)): x = data[x] print(x) ``
The correct answer is A. 0. Tracing through the loop with len(data) = 4 iterations reveals a cycle: starting at x = 0, each step follows the chain 0 → 1 → 0 → 1 → 0, so after exactly 4 iterations x lands back on 0 and that's what gets printed. B (1) is wrong because it describes the value of x after an…
Question
data = {1: 0, 2: 1, 3: 2, 0: 1}
x = 0
for _ in range(len(data)):
x = data[x]
print(x)
Options
- A0
- B1
- CThe code is erroneous.
- D2
How the community answered
(49 responses)- A84% (41)
- B10% (5)
- C2% (1)
- D4% (2)
Explanation
Tracing through the loop with len(data) = 4 iterations reveals a cycle: starting at x = 0, each step follows the chain 0 → 1 → 0 → 1 → 0, so after exactly 4 iterations x lands back on 0 and that's what gets printed. B (1) is wrong because it describes the value of x after an odd number of iterations - the loop runs an even number (4) of times, always exiting on 0. D (2) is never assigned to x at all during execution; 2 only appears as a value mapped from key 3, which is never reached in the traversal. C is wrong because the code is entirely valid - every key looked up (0 and 1 alternately) exists in the dictionary.
Memory tip: Think of it as a "pointer-chasing" trick - draw out the chain x = 0 → 1 → 0 → 1 → … and count the steps. Since the loop count is even, you always end where you started.
Community Discussion
No community discussion yet for this question.