Advanced Chapter 188 · 30 min read · Module 15: Career and Interview Preparation
Python Conceptual Interview Questions
- After this chapter you can explain mutable and immutable objects with examples.
- You can tell the difference between `==` and `is` and know when each one is right.
- You can describe the LEGB scope rule and the mutable default argument trap.
- You can explain shallow and deep copies, generators and decorators in simple words.
- You can answer questions about the GIL, `*args` and `**kwargs` and `__name__` clearly.
Interviews for Python roles rarely ask you to recite syntax. They ask why Python behaves the way it does. Why does changing a list inside a function change it outside? Why is [] == [] true but [] is [] false? Questions like these test whether you understand the model behind the language, not only the commands.
This chapter walks through the conceptual questions that appear again and again. For each topic you get a short explanation, a runnable example with its exact output, and a sentence or two that you can say in an interview. The goal is not to memorise answers, but to build a mental picture that lets you answer new questions in the same area.
As you read, try to explain each idea out loud in your own words. If you can teach it to a friend in thirty seconds, you understand it well enough for an interview.
Names, objects and mutability
In Python a variable is a name that points to an object. Assignment never copies the object; it only makes the name point to it. This is the key to many interview questions. When two names point to the same object, a change made through one name is visible through the other, but only if the object can be changed in place.
Lists, dictionaries and sets are mutable. Numbers, strings, tuples and frozensets are immutable. When you write s = s + 'x' for a string, Python builds a new string and moves the name s to it. The old string is untouched. A common follow-up question is that a tuple can hold a list, and that list can still change, because the tuple only promises that it will keep pointing at the same objects.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(a is b)
s = 'hi'
t = s
t = t + '!'
print(s, t)Equality and identity
The operator == asks whether two objects have equal values. The operator is asks whether two names point to the very same object in memory. Two separate lists with the same items are equal but not identical. Use is mainly for None, as in if x is None, because there is only one None object. Do not use is to compare numbers or strings; small values are sometimes shared by CPython as an optimisation, which makes is look correct by accident.
x = [1, 2]
y = [1, 2]
z = x
print(x == y)
print(x is y)
print(x is z)
print(id(x) == id(z))
value = None
print(value is None)Scope and the LEGB rule
When Python looks for a name it searches four places in order: Local (inside the current function), Enclosing (outer functions), Global (the module) and Built-in (names such as len). This is called the LEGB rule. Assigning to a name inside a function makes it local unless you declare it with global or nonlocal. The nonlocal keyword lets an inner function change a variable in the enclosing function, which is how closures keep state.
level = 'global'
def outer():
level = 'enclosing'
def inner():
nonlocal level
level = 'changed by inner'
inner()
return level
print(outer())
print(level)The mutable default argument trap
Default values are created once, when the def line runs, not each time the function is called. If the default is a list or dict, every call that uses the default shares the same object. The usual fix is to use None as the default and create a fresh list inside the function. Interviewers love this question because it checks that you know when default values are evaluated.
def bad(item, bucket=[]):
bucket.append(item)
return bucket
def good(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(bad(1))
print(bad(2))
print(good(1))
print(good(2))Shallow copy and deep copy
A shallow copy makes a new outer container but reuses the inner objects. A deep copy copies the inner objects too. For a flat list of numbers the difference does not matter. For a list of lists, a shallow copy still shares the inner lists, so changing an inner list shows up in both copies. Use copy.deepcopy when you need a fully independent structure.
import copy
rows = [[1, 2], [3, 4]]
shallow = rows.copy()
deep = copy.deepcopy(rows)
rows[0].append(99)
print(shallow)
print(deep)Generators and iterators
An iterator is an object that gives one value at a time through next(). A generator is an easy way to write an iterator: a function that uses yield. Each yield pauses the function and remembers its local state, so the next call continues where it stopped. Generators are lazy, which means they produce values only when asked. This saves memory when working with large or endless sequences. A generator can be used only once; after it is exhausted it gives nothing more.
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen))
print(list(gen))
print(list(gen))Decorators, *args and **kwargs
A decorator is a function that takes another function and returns a new function, usually adding behaviour before or after the original call. The @name line above a def is shorthand for func = name(func). Decorators rely on the fact that functions are objects that can be passed around. Inside a decorator you often write *args and **kwargs so that the wrapper accepts any arguments and passes them on. *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict.
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@shout
def greet(name, punct='.'):
return 'hello ' + name + punct
print(greet('asha', punct='!'))The GIL and threads
CPython has a Global Interpreter Lock, called the GIL. It lets only one thread run Python bytecode at a time. Because of this, threads do not speed up CPU-heavy pure Python code, but they work well for waiting tasks such as network or file input and output. For CPU-heavy work use the multiprocessing module, which uses separate processes, or use libraries written in C that release the lock. Recent Python versions have an experimental free-threaded build, but the standard answer in interviews is still that the GIL limits CPU-bound threading in standard CPython.
Other favourite questions
- List versus tuple: lists are mutable and used for collections that change; tuples are immutable, can be dictionary keys when their items are hashable, and signal fixed data.
- What does
if __name__ == '__main__'do: it runs code only when the file is run directly, not when it is imported. - What is a closure: an inner function that remembers variables from the enclosing function even after the outer function has finished.
- What is duck typing: Python cares about what an object can do, not its declared type.
- Is Python compiled or interpreted: source is compiled to bytecode, which the virtual machine then runs.
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step
c = make_counter()
print(c(), c(), c())
print(__name__)Python syntax
a is b # same object?
a == b # equal value?def f(x, items=None):
if items is None:
items = []def deco(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapperReal-world applications
- Answering screening questions in Python developer interviews
- Reviewing code and spotting aliasing and default-argument bugs
- Choosing between threads and processes for a program
- Writing memory-friendly pipelines with generators
- Adding logging or timing to functions with decorators
Common mistakes
is to compare strings or numbersFix: Use
== for values. Keep is for None and for checking that two names are the same object.Fix: Use
None as the default and create the new list or dict inside the function.b = a copies a listFix: Use
a.copy(), list(a) or copy.deepcopy(a) when you need a separate object.Fix: Create a new generator, or store the values in a list if you need them more than once.
Fix: Explain that the GIL limits CPU-bound threads, and suggest multiprocessing for that case.
Important tips
- Always give a tiny code example when you answer; it proves you understand.
- Start with the one-line definition, then the example, then when you would use it.
- If you do not know an answer, reason from first principles instead of guessing.
- Practise running small experiments in the REPL to confirm what you claim.
Key points summary
- Variables are names that refer to objects; assignment does not copy.
- Mutable objects change in place; immutable objects never do.
==compares values,iscompares identity.- Name lookup follows LEGB: Local, Enclosing, Global, Built-in.
- Default argument values are created once at definition time.
- Generators are lazy and single-use; decorators wrap functions.
Exam and interview points
- Name three immutable types and three mutable types.
- State the LEGB order and what
nonlocaldoes. - Explain why default arguments are evaluated once.
- Contrast shallow copy and deep copy with an example.
- Explain why the GIL matters for CPU-bound threads.
Quick revision
- Assignment binds a name, it never copies.
is None, but==for values.- LEGB: Local, Enclosing, Global, Built-in.
- Default
None, then create the list inside. yieldmakes a lazy, single-use generator.@decomeansf = deco(f).
Frequently asked questions
Is Python pass by value or pass by reference?
Neither exactly. Python passes object references by value. The function receives a reference to the same object, so changing a mutable object inside shows outside, but reassigning the parameter name does not affect the caller.
Why can a tuple contain a list that changes?
A tuple is immutable only in the sense that it cannot change which objects it holds. If one of those objects is mutable, that object can still change.
What is the difference between a generator and a list?
A list stores every value in memory at once. A generator produces values one at a time when asked, so it uses far less memory but can be read only once.
Does the GIL mean Python has no parallelism?
No. Threads are limited for CPU-bound code, but multiprocessing runs separate processes in parallel, and I/O-bound threads or async code work well.
When should I use deepcopy?
Use it when your data has nested mutable objects and you need a copy that shares nothing with the original.
Practise this chapter
16 practice questions Take the chapter quiz