ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Node:
    def __init__(self, val, children=None):
        self.val = val
        self.children = children if children is not None else []
n1 = Node(1)
n2 = Node(2)
n1.children.append(n2)
print(len(Node(3).children))
  1. A. 0
  2. B. 1
  3. C. 2
  4. D. AttributeError

Correct answer: A. 0

Using the None-sentinel pattern gives every instance that omits children its OWN fresh empty list; appending to n1.children never affects a brand-new Node(3), whose children list starts empty, length 0.

More Python Programming questions

Exams that ask this topic