ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
from collections import namedtuple
P = namedtuple("P", "x y", defaults=[0])
p = P(1)
q = p._replace(y=5)
print(p, q, p == (1, 0), q._asdict()["y"], P._fields)
  1. A. P(x=1, y=None) P(x=1, y=5) False 5 ('x', 'y')
  2. B. P(x=1, y=0) P(x=1, y=5) True 5 ('x', 'y')
  3. C. P(x=1, y=0) P(x=1, y=0) True 5 ('x', 'y')
  4. D. P(x=1, y=0) P(x=1, y=5) False 5 ['x', 'y']

Correct answer: B. P(x=1, y=0) P(x=1, y=5) True 5 ('x', 'y')

defaults apply to the rightmost fields, so y defaults to 0. _replace returns a NEW namedtuple (they are immutable). A namedtuple is a tuple, so it compares equal to a plain tuple with the same items.

More Python Programming questions

Exams that ask this topic