ProgrammingModerateGATE CS · Product-company placement

What is printed?

What is printed?
x = [3, 1, 2]
y = sorted(x)
z = reversed(x)
x.append(0)
print(y, list(z))
  1. A. [1, 2, 3] [0, 2, 1, 3]
  2. B. [1, 2, 3] [2, 1, 3]
  3. C. [0, 1, 2, 3] [0, 2, 1, 3]
  4. D. [1, 2, 3] [3, 1, 2]

Correct answer: B. [1, 2, 3] [2, 1, 3]

sorted() builds a new list immediately. reversed() returns a lazy iterator that remembers the starting index (len 3 at creation), so it yields x[2], x[1], x[0] = 2, 1, 3 and never sees the appended 0.

More Python Programming questions

Exams that ask this topic