PCEP-30-02 · Question #24
Which one of the lines should you put in the snippet below to match the expected output? Expected output: [1, 2, 4, 7] ``python 1 list = [2, 7, 1, 4] 3 # enter code here 5 print(list) ``
The correct answer is C. list.sort(). list.sort() is correct because it's an in-place method that modifies the original list directly, which is why the subsequent print(list) shows the sorted result [1, 2, 4, 7]. A (sorted(list)) returns a new sorted list but doesn't modify list itself - the result is discarded…
Question
[1, 2, 4, 7]
1 list = [2, 7, 1, 4]
3 # enter code here
5 print(list)
Options
- Asorted(list)
- Bsort(list)
- Clist.sort()
- Dlist.sorted()
How the community answered
(22 responses)- A14% (3)
- B5% (1)
- C73% (16)
- D9% (2)
Explanation
list.sort() is correct because it's an in-place method that modifies the original list directly, which is why the subsequent print(list) shows the sorted result [1, 2, 4, 7].
- A (
sorted(list)) returns a new sorted list but doesn't modifylistitself - the result is discarded since it's not assigned to anything, soprint(list)would still show the original order. - B (
sort(list)) is not valid Python syntax -sortis not a standalone built-in function, only a list method. - D (
list.sorted()) doesn't exist - lists have no.sorted()method;sorted()is a built-in function, not a method on list objects.
Memory tip: Think of the dot (.) as ownership - list.sort() means "the list sorts itself in place," while sorted(list) means "give me a sorted copy of the list." If you need to assign or return the result, use sorted(); if you want to modify the original, use .sort().
Community Discussion
No community discussion yet for this question.