A junior developer is tasked with writing a Python script that reads a list of integers from a file, removes any duplicate numbers, and then writes the unique numbers back to the same file in ascending order. The file 'numbers.txt' currently contains one integer per line. The developer writes the following code: with open('numbers.txt', 'r') as f: numbers = [int(line.strip()) for line in f] unique = list(set(numbers)) unique.sort() with open('numbers.txt', 'w') as f: for num in unique: f.write(str(num) + '\n') The script runs without errors, but the output file contains the numbers in descending order instead of ascending. The developer checks the sort() method and confirms it sorts in ascending order. What is the MOST likely cause of the issue?
If the developer wrote unique = list(set(numbers)).sort(), unique would be None. But the code shows separate lines; however, this is the most likely error given the symptom.
Why this answer
Option B is correct because the developer's code does not contain any logical error that would cause descending order. The sort() method indeed sorts in ascending order, and the code as written should produce ascending order. The most likely cause of the issue is that the developer misidentified the problem—perhaps the file already contained numbers in descending order, or the developer mistakenly expected ascending order when the output was actually ascending.
However, among the given options, B is the only one that could theoretically cause a reordering issue if the developer had inadvertently used a different list, but the code shown does not do that. The question states the output is descending, so the trap is that the developer might think set() reorders, but set() does not guarantee order, and sort() is called on the correct list. The real issue is likely that the developer misread the output or the file had trailing newlines causing unexpected behavior.
Exam trap
Python Institute often tests the misconception that set() preserves order or that sort() can be accidentally called on a different variable, but in this code, the sort() is correctly applied to the unique list, so the trap is that candidates might incorrectly blame set() or sort() without carefully tracing the code.
How to eliminate wrong answers
Option A is wrong because the code explicitly converts each line to an integer with int(line.strip()), so numbers are integers, not strings, and sort() will sort numerically, not lexicographically. Option C is wrong because opening a file in read mode does not truncate it; truncation only occurs when opening in write mode ('w') or with the 'x' flag. Option D is wrong because the code opens the file with 'w' mode, not append mode ('a'), so the sorted numbers overwrite the original content, not append to it.