6.14 Interview Questions
Frequently asked and scenario-based Python interview questions covering references, shallow vs deep copy, UnboundLocalError, the LEGB rule, and reference counting vs garbage collection.
Frequently Asked Questions
- What is the difference between a variable and an object in Python?
- Explain the difference between
isand==with an example. - What is the difference between a shallow copy and a deep copy?
- What causes an
UnboundLocalError, and how do you fix it? - Explain the LEGB rule.
- Why does Python need both reference counting and a garbage collector?
Scenario-Based Questions
- A function receives a list, appends to it, and the caller sees the change — but a similar function with an
intargument doesn’t affect the caller. Why? - You copy a list of lists with
copy.copy()and mutate a nested list — the “copy” changes too. What copy type do you need instead, and why? - A script sets an API key directly in the source code. What’s wrong with this, and what’s the fix?
Quick Interview Answer
“The core questions in this area test whether you understand that a variable is a reference, not a container:
isvs==(identity vs value), shallow vs deep copy (whether nested objects are shared),UnboundLocalError(a name assigned anywhere in a function is treated as local throughout it), the LEGB scope-resolution order, and why reference counting alone can’t free reference cycles, which is what the supplementary cyclic garbage collector exists for. The scenario questions usually come down to one root cause: mutable objects are shared through references, immutable ones are not.”
Common Mistakes
- Answering “Python passes by reference” or “by value” for function arguments instead of the more precise “pass by object reference” — see 6.10 Variables in Functions.
- Explaining shallow vs deep copy only in the abstract, without being able to walk through what happens to a nested list under each — see 6.5 Copying Objects.
- Not being able to explain why
UnboundLocalErrorhappens (Python decides a name is local for the whole function if it’s assigned anywhere in it), only that it’s “a scoping bug.”
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form