PCEP-30-02 · Question #218
``python def fun(n): x = [] for i in range(n): x.append(i) return x print(fun(4)) `` What is the expected output of the following code?
The correct answer is C. [0, 1, 2, 3]. Option C is correct because range(4) generates the sequence 0, 1, 2, 3 - starting at 0 and stopping before 4 - and each value is appended one by one to the list x, which is returned and printed as [0, 1, 2, 3]. Option A is wrong because no value is ever repeated or set to 4…
Question
def fun(n):
x = []
for i in range(n):
x.append(i)
return x
print(fun(4))
What is the expected output of the following code?Options
- A[4, 4, 4, 4]
- B0 1 2 3
- C[0, 1, 2, 3]
- DThe program will cause an error.
How the community answered
(37 responses)- A3% (1)
- B14% (5)
- C73% (27)
- D11% (4)
Explanation
Option C is correct because range(4) generates the sequence 0, 1, 2, 3 - starting at 0 and stopping before 4 - and each value is appended one by one to the list x, which is returned and printed as [0, 1, 2, 3]. Option A is wrong because no value is ever repeated or set to 4; each iteration appends a different i. Option B describes what you'd see if print(i) were called inside the loop on each iteration, not what happens when a completed list is returned and printed once. Option D is wrong because the code is syntactically and logically valid - there is no error.
Memory tip: Think of range(n) as a countdown that never reaches n - it always starts at 0 and stops at n-1, giving you exactly n values.
Community Discussion
No community discussion yet for this question.