ProgrammingHardTCS NQT · Wipro pattern

What is printed?

What is printed?
x = [1] * 3
for i in range(3):
    x[i] = x[i - 1] + i
print(x)
  1. A. [1, 2, 3]
  2. B. [1, 1, 2]
  3. C. IndexError
  4. D. [1, 2, 4]

Correct answer: D. [1, 2, 4]

On the first pass x[i - 1] is x[-1], the LAST element (1), not an error: x[0] = 1 + 0 = 1. Then x[1] = 1 + 1 = 2 and x[2] = 2 + 2 = 4.

More Python Programming questions

Exams that ask this topic