PCEP-30-02 · Question #179
What is the expected output of the following code? def get_names(): names = ['Peter', 'Paul', 'Mary', 'Jane', 'Steve'] return names[2:] def update_names(names): res = [] for name in names…
The correct answer is C. ['MAR', 'JAN', 'STE']. get_names() uses names[2:] to slice the list starting at index 2 (zero-based), returning ['Mary', 'Jane', 'Steve'] - not the first two elements, but everything from the third onward. Then update_names() applies name[:3].upper() to each, taking the first 3 characters and…
Question
Options
- A['JA', 'ST']
- B['MA', 'JA', 'ST']
- C['MAR', 'JAN', 'STE']
- D['JAN', 'STE']
How the community answered
(36 responses)- A14% (5)
- B3% (1)
- C75% (27)
- D8% (3)
Explanation
get_names() uses names[2:] to slice the list starting at index 2 (zero-based), returning ['Mary', 'Jane', 'Steve'] - not the first two elements, but everything from the third onward. Then update_names() applies name[:3].upper() to each, taking the first 3 characters and uppercasing them: 'Mary'[:3] → 'MAR', 'Jane'[:3] → 'JAN', 'Steve'[:3] → 'STE', giving ['MAR', 'JAN', 'STE'].
Why the distractors fail:
- A and B use only 2 characters per name (
name[:2]), not 3 - a confusion between[:2]and[:3]. - A and D are also missing
'Mary'/'MAR', suggesting a misread ofnames[2:]as "skip the first three" rather than "start at index 2." - D gets the 3-character slice right but incorrectly starts the slice at index 3 instead of 2, dropping
'Mary'.
Memory tip: Think of Python slicing as [start:stop] where start is included - so names[2:] means "give me element 2 and everything after it," not "skip 2 elements." Pair that with [:3] meaning "the first 3 characters (indices 0, 1, 2)," and you'll nail both slices every time.
Community Discussion
No community discussion yet for this question.