All sample questions / Python
Python Mutability, References and Copying, what does print(data) print after def grow(lst)?
Block 7, Mutability, References and Copying, question 7 of the Python sample
def grow(lst):
lst = lst + [99]
data = [1, 2]
grow(data)
print(data)
What does this print?
Show the answer and why each option is right or wrong
Answer, B. [1, 2]
- A. [1, 2, 99]
- Confuses this with the augmented case, assuming the caller sees the extra element as well.
- B. [1, 2]
- Correct. lst + [99] builds a new list and the assignment only rebinds the local name lst, it never touches the list object that data still refers to.
- C. [99]
- Assumes only the freshly built list survives and the caller ends up holding it instead of its original list.
- D. []
- Assumes rebinding a parameter inside a function clears the caller variable.
Unlike +=, the plain + operator never mutates its operands, it always produces a new list. Assigning that new list to the local name lst only changes what lst refers to inside the function, the caller variable data was never touched and keeps pointing at the original two element list after the function returns.
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.