All sample questions / Python

Python Scope, Functions and Closures, what does print(data) print after def clear_it(container)?

Block 2, Scope, Functions and Closures, question 8 of the Python sample

def clear_it(container):
    container.clear()
data = {'a': 1, 'b': 2}
clear_it(data)
print(data)

What does this print?

  1. A. {'a': 1}
  2. B. {}
  3. C. {'a': 1, 'b': 2}
  4. D. None
Show the answer and why each option is right or wrong

Answer, B. {}

A. {'a': 1}
Assumes clear only removes one arbitrary entry from the dictionary rather than removing every key it contains.
B. {}
Correct. container refers to the same dictionary object as data, so calling clear on it empties that shared dictionary of every key it held, which is why data prints as an empty dictionary afterward.
C. {'a': 1, 'b': 2}
Assumes the function operates on a private copy of the dictionary, so calling clear on it never affects the caller's own dictionary.
D. None
Confuses the fact that clear_it has no return value with the idea that data itself gets replaced by that same None.

Methods like clear that mutate a mutable object in place affect every name that refers to that same object, since there is only ever one underlying object being changed. This is the same sharing behavior that makes append on a shared list or a key assignment on a shared dictionary visible through any reference to that object.

The answer above is what the CPython interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 Python interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 Python questions, 9 euros

Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros

Or play the free Python sample, twenty questions in the browser, also as a free PDF.

Previous question Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.