nerdexam
Python_Institute

PCEP-30-02 · Question #8

How would you remove all the items from the d dictionary? Expected output: `` {} ` Code: `python d = {'A' : 1, 'B' : 2, 'C' : 3} ``

The correct answer is D. d.clear(). d.clear() is the correct method because it empties the dictionary in place, leaving the original object intact but with no key-value pairs - exactly producing {}. A (d.del()) - no such method exists on dictionaries; this raises AttributeError. B (d.remove()) - also nonexistent…

Question

How would you remove all the items from the d dictionary? Expected output:
{}
Code:
d = {'A' : 1, 'B' : 2, 'C' : 3}

Options

  • Ad.del()
  • Bd.remove()
  • Cdel d
  • Dd.clear()

How the community answered

(28 responses)
  • A
    4% (1)
  • B
    14% (4)
  • C
    7% (2)
  • D
    75% (21)

Explanation

d.clear() is the correct method because it empties the dictionary in place, leaving the original object intact but with no key-value pairs - exactly producing {}.

  • A (d.del()) - no such method exists on dictionaries; this raises AttributeError.
  • B (d.remove()) - also nonexistent on dicts; remove() exists on lists, not dictionaries.
  • C (del d) - this deletes the variable itself from the namespace entirely, so d would no longer exist at all rather than becoming {}.

Memory tip: Think of .clear() like clearing a whiteboard - the board (the dictionary object) is still there, just wiped clean. del d throws the whole whiteboard away.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice