PCEP-30-02 · Question #31
What is the output of the following snippet? ``python my_list = ['Mary', 'had', 'a', 'little', 'lamb'] del my_list[3] my_list[3] = 'ram' print(my_list) ``
The correct answer is B. ['Mary', 'had', 'a', 'ram']. Option B is correct because del my_list[3] removes 'little' (index 3), shrinking the list to ['Mary', 'had', 'a', 'lamb'] - now 'lamb' sits at index 3. The next line my_list[3] = 'ram' then replaces 'lamb' with 'ram', yielding ['Mary', 'had', 'a', 'ram']. Why the distractors…
Question
my_list = ['Mary', 'had', 'a', 'little', 'lamb']
del my_list[3]
my_list[3] = 'ram'
print(my_list)
Options
- A['Mary', 'had', 'a', 'little', 'lamb']
- B['Mary', 'had', 'a', 'ram']
- C['Mary', 'had', 'a', 'lamb', 'ram']
- DNo output, the snippet is erroneous
How the community answered
(63 responses)- A5% (3)
- B81% (51)
- C11% (7)
- D3% (2)
Explanation
Option B is correct because del my_list[3] removes 'little' (index 3), shrinking the list to ['Mary', 'had', 'a', 'lamb'] - now 'lamb' sits at index 3. The next line my_list[3] = 'ram' then replaces 'lamb' with 'ram', yielding ['Mary', 'had', 'a', 'ram'].
Why the distractors are wrong:
- A ignores both mutations and returns the original list - a trap for anyone who misses that
deland assignment both execute. - C would require
'lamb'to survive and'ram'to be inserted after it, butdelshortens the list first and the=assignment replaces, not inserts. - D is wrong because the code is perfectly valid - after
del, index 3 is within bounds (the list has 4 elements), so noIndexErroris raised.
Memory tip: Think of it as a two-step swap - del evicts the tenant at slot 3, sliding everyone behind it forward, then = moves a new tenant in to that now-vacant slot.
Community Discussion
No community discussion yet for this question.