PCEP-30-02 · Question #200
What is the expected output of the following code? data = 'abcdefg' def func(text): del text[2] return text print(func(data))
The correct answer is B. The code is erroneous. Option B is correct because Python strings are immutable - once created, their contents cannot be changed in place. Calling del text[2] on a string raises a TypeError: 'str' object doesn't support item deletion, so the function never returns and the program crashes. The…
Question
Options
- Aacdef
- BThe code is erroneous.
- Cabdef
- Dabcef
How the community answered
(27 responses)- A11% (3)
- B81% (22)
- C4% (1)
- D4% (1)
Explanation
Option B is correct because Python strings are immutable - once created, their contents cannot be changed in place. Calling del text[2] on a string raises a TypeError: 'str' object doesn't support item deletion, so the function never returns and the program crashes.
The distractors fail for two reasons: first, they assume deletion is possible at all; second, none of them even reflect the right character being removed. Deleting index 2 (which is 'c') from 'abcdefg' would yield 'abdefg' - yet option A (acdef) skips 'b' and truncates the string, option C (abdef) is missing both 'c' and 'g', and option D (abcef) looks like 'd' (index 3) was deleted instead.
Memory tip: Think "strings are read-only in Python." If you need to remove a character, use slicing - text[:2] + text[3:] - or convert to a list first. Any attempt to mutate a string directly (via del, index assignment like text[2] = 'x', etc.) will always raise a TypeError.
Community Discussion
No community discussion yet for this question.