PCEP-30-02 · Question #11
Which one of the lines should you put in the snippet below to match the expected output? Expected output: `` [4, 1, 7, 2, 'A'] ` Code: `python list = ['A', 2, 7, 1, 4] enter code here print(list) ``
The correct answer is C. C. list.reverse(). Option C, list.reverse(), is correct because it's a built-in list method that reverses the list in-place - meaning it modifies the original list directly and returns None, which is exactly what's needed here since the code then prints list. Why the distractors fail: A…
Question
[4, 1, 7, 2, 'A']
Code:
list = ['A', 2, 7, 1, 4]
# enter code here
print(list)
Options
- AA. reverse(list)
- BB. list.reversed()
- CC. list.reverse()
- DD. reversed(list)
How the community answered
(41 responses)- A5% (2)
- B15% (6)
- C73% (30)
- D7% (3)
Explanation
Option C, list.reverse(), is correct because it's a built-in list method that reverses the list in-place - meaning it modifies the original list directly and returns None, which is exactly what's needed here since the code then prints list.
Why the distractors fail:
- A (
reverse(list)) -reverseis not a standalone built-in function in Python; this raises aNameError. - B (
list.reversed()) -reversedis not a list method; calling it this way raises anAttributeError. - D (
reversed(list)) - This is a valid built-in function, but it returns a reverse iterator object, not a list, and it doesn't modifylistin place - soprint(list)would still show the original order.
Memory tip: Think of it as the method vs. function distinction - list.reverse() (method, no return value, modifies in place) vs. reversed(list) (built-in function, returns an iterator, original untouched). If you need to modify and print the same variable, the method is your answer.
Community Discussion
No community discussion yet for this question.