ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
class Node:
    def __init__(self, v, nxt=None): self.v, self.nxt = v, nxt
    def __iter__(self):
        n = self
        while n:
            yield n.v
            n = n.nxt
lst = Node(1, Node(2, Node(3)))
def rev(n, prev=None):
    while n:
        n.nxt, prev, n = prev, n, n.nxt
    return prev
print(list(lst), list(rev(lst)), list(lst))
  1. A. [1, 2, 3] [3, 2, 1] [1, 2, 3]
  2. B. [1, 2, 3] [3, 2, 1] [1]
  3. C. [1, 2, 3] [3, 2, 1] [3, 2, 1]
  4. D. [1, 2, 3] [1] [1]

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

The tuple assignment evaluates (prev, n, n.nxt) first and then assigns n.nxt, prev, n left to right, which correctly reverses the list in place. Afterwards the old head (1) is the tail, so iterating from it yields only [1].

More Python Programming questions

Exams that ask this topic