ProgrammingVery hardWipro · Accenture · Capgemini pattern

What does the following Python 3 code print? class Stack: def __init__(self): self._items = [] def __len__(self): return len(self._items) def __bool__(self): return len(self._items) > 0 def push(self, x): self._items.append(x) s = Stack() print(bool(s)) s.push(1) print(bool(s), len(s))

  1. A. False False 1
  2. B. True True 1
  3. C. False True 1
  4. D. False True 0

Correct answer: C. False True 1

bool() calls __bool__ which checks the underlying list; empty gives False, and after one push it has length 1, so bool is True.

More Python Programming questions

Exams that ask this topic