All sample questions / Python
Python Mutability, References and Copying, what does print(items) print after def add_item(lst)?
Block 7, Mutability, References and Copying, question 10 of the Python sample
def add_item(lst):
lst.append('x')
items = ['a', 'b']
add_item(items)
print(items)
What does this print?
Show the answer and why each option is right or wrong
Answer, B. ['a', 'b', 'x']
- A. ['a', 'b']
- Assumes the function receives a private copy of the list, so the caller would not see the appended value.
- B. ['a', 'b', 'x']
- Correct. The parameter lst is bound to the same list object as items, so the append call inside the function mutates the caller's list directly.
- C. ['x']
- Assumes lst starts as its own empty list rather than aliasing the caller's list.
- D. ['a', 'b', 'x', 'x']
- Assumes the append is somehow applied twice, once inside the function and once after it returns.
Python passes arguments by assigning the caller object to the parameter name, it never copies the argument. A mutable object like a list can therefore be changed from inside a function and the caller will observe the change, because the parameter and the caller variable are two names for one 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.