nerdexam
Python_Institute

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

What is the output of the following snippet?
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)
  • A
    5% (3)
  • B
    81% (51)
  • C
    11% (7)
  • D
    3% (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 del and assignment both execute.
  • C would require 'lamb' to survive and 'ram' to be inserted after it, but del shortens 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 no IndexError is 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.

Full PCEP-30-02 Practice