π€ Python Interview Questions
in Python
Forty-one Python interview questions with clear answers and runnable demos: mutable defaults, is vs ==, copies, closures, generators, GIL, testing, algorithms.
What this lesson is about
A Python interview is rarely a quiz on obscure syntax. Interviewers usually want to know whether you understand how the language behaves: what happens when you pass a list into a function, why two names can point at one object, what a decorator really returns. The questions on this page are the ones that keep coming back because they separate people who have memorised snippets from people who can predict what code will do.
I have grouped forty-one questions into eight themes: basics and data types, functions and scope, object-oriented programming, memory and performance, iterators, generators and decorators, concurrency and the GIL, testing and tooling, and short algorithm warm-ups. Each theme has a short written answer for every question and then runnable demos that I explain line by line, so you can change a line and watch the behaviour change. Saying an answer aloud is good practice, but running it is better.
Use the page in two passes. First read the answers and try to say them in your own words without looking. Then run the demos and predict the output before you press Run. When a topic feels shaky, follow the link to the full lesson, for example Python data types, functions or scope and closures. Nothing here replaces writing code, so pair it with the practice exercises.
What you will learn
- βExplain mutable versus immutable objects and
isversus==with evidence - βPredict the mutable default argument and late-binding closure surprises
- βDescribe the LEGB rule and when
globalornonlocalis needed - βAnswer class design questions: class attributes, MRO,
classmethod,__repr__ - βCompare shallow and deep copies, reference counting and
__slots__ - βExplain generators, laziness and why
functools.wrapsmatters - βChoose between threads, processes and asyncio, and say what the GIL does
- βSolve classic warm-ups: two-sum, anagrams, Fibonacci with caching, binary search
Why programmers should learn this
- β Interviewers use these questions because the answers reveal whether you understand Python's object model, which is what prevents real bugs such as shared default lists.
- β Being able to demonstrate an answer with five lines of code is far more convincing than reciting a definition, and the demos here are exactly that size.
- β Many of these topics, such as closures, generators and the GIL, also decide how you design production code, so learning them for an interview pays off afterwards.
- β Spoken explanations improve when you have run the code yourself; nervousness is easier to manage when you have seen the real output several times.
- β The questions map onto a typical junior-to-mid screening process, so you can use the eight sections as a revision checklist and see which themes need more study.
Section 1: Basics and data types
Q1. What is the difference between mutable and immutable objects? A mutable object can be changed in place after creation: lists, dictionaries, sets and most user-defined class instances. An immutable object cannot: integers, floats, strings, tuples, frozensets and bytes. When you 'change' an immutable value, such as s = s + 'x', Python builds a new object and rebinds the name. This matters because mutable objects can be modified through any reference, which is the root of many surprises later in this page.
Q2. What is the difference between is and ==? == asks whether two objects have equal values by calling __eq__. is asks whether two names refer to the very same object. Two separate lists with the same contents are equal but not identical. Use is for singletons, and in practice that means is None, is True rarely, and never for comparing numbers or strings. Whether two equal small integers happen to be the same object is an implementation detail, so a good answer says 'do not rely on it'.
Q3. How do lists, tuples, sets and dictionaries differ, and when would you pick each? A list is an ordered, mutable sequence for collections you append to. A tuple is an ordered, immutable sequence, good for fixed records and usable as a dictionary key if its items are hashable. A set stores unique hashable items with fast membership tests and no order you should rely on. A dictionary maps hashable keys to values. See lists, tuples, sets and dictionaries for the full tour.
Q4. Are dictionaries ordered? Yes. Since Python 3.7 the language guarantees that a dictionary remembers insertion order. Two dictionaries compare equal when they hold the same key-value pairs, regardless of order, which is a favourite follow-up. Note that sets do not make the same promise.
Q5. Why does 0.1 + 0.2 == 0.3 evaluate to False, and how do you handle it? Floats are binary approximations, and neither 0.1 nor 0.2 has an exact binary representation, so the sum lands a hair away from 0.3. For comparisons use math.isclose; for money use decimal.Decimal built from strings, or integer cents. Q6. What counts as falsy? None, False, zero of any numeric type, and empty containers or strings. Everything else is truthy unless a class defines __bool__ or __len__. A strong answer adds that if items: is idiomatic, but if x: is wrong when zero is a valid value.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)
c.append(4)
print(a)
name = "py"
longer = name + "thon"
print(name, longer)
d1 = {"x": 1, "y": 2}
d2 = {"y": 2, "x": 1}
print(d1 == d2, list(d1), list(d2))
import math
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
for value in [0, "", [], None, 0.0, "0", [0]]:
print(repr(value), bool(value))True False True [1, 2, 3, 4] py python True ['x', 'y'] ['y', 'x'] False True 0 False '' False [] False None False 0.0 False '0' True [0] True
Line by line
- 1-3
aandbare two separate lists with equal contents.c = adoes not copy: it adds a second name for the same list. - 5Equal values (
True), different objects (False), same object (True). - 7-8Appending through
cchanges the one shared list, so printingashows the 4. - 10-12Strings are immutable:
+builds a brand-new string andnamestill points at the old one. - 14-16Dictionaries compare by content, so key order does not affect
==, but iteration order still follows insertion order, which is why the two lists of keys differ. - 18-19The classic float surprise, and
math.iscloseas the sound comparison. - 20-21Loop over seven values and print their truthiness. Note that the string
"0"and the list[0]are truthy because they are not empty.
Section 2: Functions and scope
Q7. What is the mutable default argument problem? Default values are evaluated once, when the def statement runs, not each time you call the function. If the default is a list or dictionary, every call that omits the argument shares the same object, so changes leak between calls. The fix is to use None as the default and create the fresh object inside the function. This is probably the single most asked Python question, so have the code ready.
Q8. What is the LEGB rule? When Python looks up a name it searches four scopes in order: Local (the current function), Enclosing (any outer functions), Global (the module) and Built-in (names like len). The first match wins. Assigning to a name inside a function makes it local for the whole function body, which is why reading it before the assignment raises UnboundLocalError. Use global to rebind a module-level name and nonlocal to rebind an enclosing function's name, though needing either is often a sign to restructure. The longer version is in scope and closures.
Q9. What is a closure, and what is late binding? A closure is a function that remembers variables from the scope where it was defined. The catch is that it remembers the variable, not its value at creation time. Lambdas created in a loop all look up the loop variable when called, after the loop has finished, so they all see its final value. The fixes are a default argument (lambda i=i: i) or a factory function that gives each closure its own scope.
**Q10. What do *args and kwargs do? In a definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. In a call, * and unpack a sequence or mapping into arguments. Together they let a wrapper function forward everything to another function without knowing its signature; see args and kwargs. Q11. Are arguments passed by value or by reference?** Neither label is quite right. Python passes references to objects, often called 'pass by object reference' or 'pass by assignment'. The function gets a new name bound to the same object, so mutating it is visible to the caller, but rebinding the parameter is not.
def add_bad(item, bucket=[]):
bucket.append(item)
return bucket
print(add_bad(1))
print(add_bad(2))
def add_good(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_good(1))
print(add_good(2))
late = [lambda: i for i in range(3)]
print([f() for f in late])
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])
def rebinder(values):
values.append("changed")
values = ["new list"]
return values
original = ["start"]
print(rebinder(original), original)[1] [1, 2] [1] [2] [2, 2, 2] [0, 1, 2] ['new list'] ['start', 'changed']
Line by line
- 1-3
bucket=[]is created once when the function is defined, and every call without an argument reuses it. - 5-6The second call returns
[1, 2]because the first call's item is still there. - 8-13The fix: default to
Noneand build a new list inside, so every call starts clean. - 15-16Each call prints a fresh single-item list.
- 18-19Three lambdas all read the same
i, which is2once the loop ends, so the list is[2, 2, 2]. - 21-22Binding
ias a default argument captures the current value for each lambda, giving[0, 1, 2]. - 24-27
appendmutates the caller's list, butvalues = [...]only rebinds the local name. - 29-30The function returns the new list, while
originalkeeps the mutation, so both facts show in one line.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
return x
def uses_enclosing():
return x
def counter_factory():
count = 0
def bump():
nonlocal count
count += 1
return count
return bump
bump = counter_factory()
return inner(), uses_enclosing(), bump(), bump()
print(outer())
print(x, len("abc"))
def broken():
try:
print(total)
except UnboundLocalError as err:
print("UnboundLocalError")
total = 1
broken()('local', 'enclosing', 1, 2)
global 3
UnboundLocalErrorLine by line
- 1A module-level (global) name.
- 4-8
innerassigns its ownx, so it finds the local one first. - 10-11
uses_enclosingnever assignsx, so lookup climbs toouter'sx. - 13-19A closure counter:
nonlocalletsbumprebindcountin the enclosing scope instead of creating a local. - 21-22Call everything and return the results as a tuple. The two
bump()calls print 1 then 2. - 24-25The global
xis untouched, andlenis found in the built-in scope. - 27-32Because
total = 1appears later in the function,totalis local throughout, so reading it earlier raisesUnboundLocalError, which we catch to show the message.
Section 3: Object-oriented programming
Q12. What is the difference between a class attribute and an instance attribute? A class attribute is defined in the class body and shared by every instance; an instance attribute is set on self, usually in __init__, and belongs to one object. Reading obj.attr checks the instance first, then the class. Assigning obj.attr = v always creates or updates the instance attribute, which shadows the class one. Mutating a shared mutable class attribute, such as a list, affects every instance, a cousin of the mutable default bug. See classes for the basics.
Q13. What do @classmethod and @staticmethod do? A regular method receives the instance as self. A class method receives the class as cls, which makes it ideal for alternative constructors such as Date.from_string(...) that also work correctly in subclasses. A static method receives neither; it is just a function placed in the class namespace for organisation. If you never touch self or cls, ask yourself whether it should be a plain module-level function instead.
Q14. What is the method resolution order (MRO)? With multiple inheritance Python needs a deterministic order in which to search base classes. It uses C3 linearisation, which keeps each class before its parents and preserves the order you listed the bases. You can inspect it with Class.__mro__. super() does not mean 'the parent'; it means 'the next class in the MRO', which is what makes cooperative multiple inheritance, including the diamond shape, work. More on inheritance is in the inheritance lesson.
Q15. What is the difference between __repr__ and __str__? __repr__ is for developers: an unambiguous representation, ideally one that looks like the code that would recreate the object. __str__ is for readers: a friendly display used by print and str(). If only __repr__ is defined, Python uses it for both. Write __repr__ first. Q16. If you define __eq__, what happens to __hash__? Python sets __hash__ to None, making instances unhashable, because equal objects must have equal hashes. If the object is meant to be a dictionary key or set member, define __hash__ consistently with __eq__ and keep the fields it uses immutable; a frozen dataclass does this for you. See also dunder methods.
class Dog:
species = "Canis"
tricks = []
def __init__(self, name):
self.name = name
def learn(self, trick):
self.tricks.append(trick)
a, b = Dog("Rex"), Dog("Fido")
a.learn("sit")
print(b.tricks)
a.species = "Wolf"
print(a.species, b.species, Dog.species)
class Date:
def __init__(self, y, m, d):
self.y, self.m, self.d = y, m, d
@classmethod
def from_string(cls, text):
y, m, d = map(int, text.split("-"))
return cls(y, m, d)
def __repr__(self):
return f"{type(self).__name__}({self.y}, {self.m}, {self.d})"
def __str__(self):
return f"{self.y:04d}/{self.m:02d}/{self.d:02d}"
class Event(Date):
pass
e = Event.from_string("2026-03-09")
print(repr(e), str(e))
class A:
def hello(self): return ["A"]
class B(A):
def hello(self): return ["B"] + super().hello()
class C(A):
def hello(self): return ["C"] + super().hello()
class D(B, C):
def hello(self): return ["D"] + super().hello()
print(D().hello())
print([k.__name__ for k in D.__mro__])['sit'] Wolf Canis Canis Event(2026, 3, 9) 2026/03/09 ['D', 'B', 'C', 'A'] ['D', 'B', 'C', 'A', 'object']
Line by line
- 1-3
speciesandtricksare class attributes shared by all dogs. - 5-9
learnappends toself.tricks, which finds the shared class list because no instance list exists. - 11-13Teaching
aa trick also shows up onb, the shared-mutable-attribute trap. - 14-15Assigning
a.speciescreates an instance attribute foraonly;band the class still sayCanis. - 17-26
Datestores three numbers and offersfrom_stringas an alternative constructor that buildscls(...). - 28-29
__repr__looks like code;__str__is a human display with zero padding. - 31-35
Eventinheritsfrom_string, and because it usescls, the result is anEvent, not aDate. - 37-45A diamond:
DinheritsBandC, both of which inheritA. Each method callssuper(). - 47-48The output
['D', 'B', 'C', 'A']shows thatsuper()inBcalledC, notA, because it follows the MRO printed on the next line.
Section 4: Memory and performance
Q17. What is the difference between a shallow copy and a deep copy? A shallow copy (list.copy(), slicing, copy.copy) creates a new outer container but reuses the same inner objects. A deep copy (copy.deepcopy) recursively copies everything it can reach. If your list holds only immutable items the two behave alike; with nested lists, a shallow copy shares the inner lists, so changing an inner list shows up in both copies. Deep copies cost more time and memory and can be unnecessary if you restructure the data.
Q18. How does Python manage memory? CPython keeps a reference count on every object. When the count reaches zero the object is freed immediately, which is why a del on the last reference runs __del__ right away in CPython. Reference counting cannot free cycles, such as two objects pointing at each other, so a cyclic garbage collector runs periodically to find them. Other implementations may behave differently, so do not rely on exactly when cleanup happens; use context managers for resources like files. The deeper story is in the GIL and memory lesson.
Q19. What does __slots__ do? Normally each instance stores its attributes in a per-instance dictionary. Declaring __slots__ = ('x', 'y') replaces that dictionary with fixed slots, which saves memory when you create very many small objects and also stops you from accidentally adding new attributes. The trade-offs are no arbitrary attributes, extra care with inheritance and no default __weakref__ unless you add it. Mention that it is an optimisation to measure, not a default.
Q20. Why is x in some_set faster than x in some_list? A set hashes the item and jumps to the right bucket, which is O(1) on average. A list compares against each element in turn, which is O(n). With one thousand items that difference is invisible; with millions of lookups it is decisive. Converting a list to a set once and then testing many times is a common optimisation, and Big O notation gives the vocabulary for explaining it. For queues, collections.deque gives O(1) pops from the left, where list.pop(0) is O(n); see collections and itertools.
Q21. Why prefer ''.join(parts) to repeated += on strings? Strings are immutable, so each concatenation can create a new string and copy the old contents. CPython sometimes optimises this, but you cannot count on it in every implementation, whereas join computes the total size once and copies each piece once. A related answer: build a list and join at the end. Always say you would measure with a profiler before optimising; the debugging and profiling lesson shows how.
import copy
grid = [[1, 2], [3, 4]]
shallow = grid.copy()
deep = copy.deepcopy(grid)
grid[0].append(99)
print(grid)
print(shallow)
print(deep)
print(shallow[0] is grid[0], deep[0] is grid[0])
class Plain:
def __init__(self, x):
self.x = x
class Slim:
__slots__ = ("x",)
def __init__(self, x):
self.x = x
p, s = Plain(1), Slim(1)
print(hasattr(p, "__dict__"), hasattr(s, "__dict__"))
p.extra = "ok"
try:
s.extra = "nope"
except AttributeError:
print("Slim rejects new attributes")[[1, 2, 99], [3, 4]] [[1, 2, 99], [3, 4]] [[1, 2], [3, 4]] True False True False Slim rejects new attributes
Line by line
- 1
copyprovides both copy functions. - 3-5
shallowis a new outer list holding the same two inner lists;deepcopies the inner lists as well. - 7Mutate the first inner list through the original.
- 8-10
gridandshallowboth show the 99 because they share the inner list;deepis unaffected. - 11Identity check confirming it: the shallow copy's first row is the very same object, the deep copy's is not.
- 13-15A normal class keeps attributes in a per-instance dictionary.
- 17-20
Slimdeclares fixed slots, so there is no__dict__. - 22-23Create one of each and ask whether they have a
__dict__:True False. - 24-28Adding an attribute works on the normal class but raises
AttributeErroron the slotted one, which we catch and report.
class Noisy:
def __init__(self, label):
self.label = label
def __del__(self):
print("freed", self.label)
first = Noisy("first")
alias = first
del first
print("still alive")
del alias
print("after last reference")
def linear_find(items, target):
steps = 0
for item in items:
steps += 1
if item == target:
break
return steps
data = list(range(1000))
print("list steps:", linear_find(data, 999))
lookup = set(data)
print("set lookups: 1 hash probe,", 999 in lookup)
from collections import deque
queue = deque([1, 2, 3])
queue.appendleft(0)
print(queue.popleft(), list(queue))still alive freed first after last reference list steps: 1000 set lookups: 1 hash probe, True 0 [1, 2, 3]
Line by line
- 1-5A class whose
__del__announces when CPython frees the object. - 7-9Two names, one object.
del firstremoves only one reference, so nothing is freed andstill aliveprints. - 10-11Deleting the last reference frees the object at once in CPython, so
freed firstappears before the next message. - 13-19A linear search that counts its comparisons instead of timing them, so the output is always the same.
- 21-22Finding the last item of 1000 takes 1000 comparisons.
- 24-25A set computes a hash and jumps to a bucket, so the lookup needs no scan.
- 27-30A
dequeadds and removes at either end in constant time;popleftreturns0and the rest remain.
Section 5: Iterators, generators and decorators
Q22. What is the difference between an iterable and an iterator? An iterable can produce an iterator when you call iter() on it, by implementing __iter__. An iterator implements __next__ to return the next value and raises StopIteration when finished, and its __iter__ returns itself. Lists are iterables but not iterators; calling iter(list) gives a list iterator. An iterator can be consumed only once, so looping over it a second time yields nothing. See the full iterators lesson.
Q23. What is a generator, and why is it lazy? A generator function contains yield. Calling it does not run the body; it returns a generator object. Each next() resumes the body until the next yield, then pauses with all local state intact. Because values are produced on demand you can process huge or infinite streams in constant memory. A generator expression such as (n * n for n in data) is the lazy cousin of a list comprehension, which builds the whole list at once; see comprehensions.
Q24. How is yield different from return? return ends the function and discards its local state. yield hands back a value and suspends, so the function can continue where it stopped. A generator can yield many values and finishes when it returns or runs off the end. Q25. What is a decorator? A function that takes a function and returns a replacement, usually a wrapper that adds behaviour such as logging, timing, caching or access checks. The @name syntax above a def is shorthand for func = name(func). The longer lesson is decorators.
Q26. Why use functools.wraps in a decorator? The wrapper function replaces the original, so without help the decorated function's __name__, __doc__ and other metadata become those of the wrapper. That breaks documentation tools, debugging output, logging and introspection. @functools.wraps(func) copies the metadata onto the wrapper and sets __wrapped__ so you can reach the original. Say that a decorator with arguments needs one more layer: a function that returns the actual decorator.
def countdown(n):
print("start")
while n > 0:
print("about to yield", n)
yield n
n -= 1
print("done")
gen = countdown(2)
print("created, nothing has run yet")
print(next(gen))
print(next(gen))
try:
next(gen)
except StopIteration:
print("StopIteration")
squares = (n * n for n in range(4))
print(list(squares))
print(list(squares))
numbers = [10, 20]
it = iter(numbers)
print(next(it), next(it))
print(iter(numbers) is numbers, iter(it) is it)created, nothing has run yet start about to yield 2 2 about to yield 1 1 done StopIteration [0, 1, 4, 9] [] 10 20 False True
Line by line
- 1-7A generator with print statements so you can see exactly when its body executes.
- 9-10Calling
countdown(2)only builds the generator object.startis not printed yet. - 11The first
nextruns the body up to the firstyield: it printsstart,about to yield 2, then returns 2. - 12The second resumes after the
yield, decrementsn, and yields 1. - 13-16The third resumes, the loop ends,
doneprints andStopIterationis raised, which theforloop machinery normally hides. - 18-20A generator expression is single-use: the second
list(squares)is empty because the first consumed it. - 22-24
iter(list)makes a fresh iterator; twonextcalls take both values. - 25A list is not its own iterator, but an iterator is:
False True.
import functools
def shout_plain(func):
def wrapper(*args, **kwargs):
"""wrapper doc"""
return str(func(*args, **kwargs)).upper()
return wrapper
def shout(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return str(func(*args, **kwargs)).upper()
return wrapper
@shout_plain
def greet_a(name):
"""Greet someone."""
return "hello " + name
@shout
def greet_b(name):
"""Greet someone."""
return "hello " + name
print(greet_a("sam"), greet_a.__name__, greet_a.__doc__)
print(greet_b("sam"), greet_b.__name__, greet_b.__doc__)
print(greet_b.__wrapped__("sam"))
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return [func(*args, **kwargs) for _ in range(times)]
return wrapper
return decorator
@repeat(3)
def ping():
return "ping"
print(ping())HELLO SAM wrapper wrapper doc HELLO SAM greet_b Greet someone. hello sam ['ping', 'ping', 'ping']
Line by line
- 3-7A decorator without
wraps: the innerwrappertakes any arguments, calls the original and upper-cases the result. - 9-13The same decorator with
@functools.wraps(func), which copies name and docstring onto the wrapper. - 15-23
@shout_plainmeansgreet_a = shout_plain(greet_a), and likewise forgreet_b. - 25The plain version reports the wrapper's name and docstring:
wrapper wrapper doc. - 26The
wrapsversion keepsgreet_bandGreet someone.. - 27
__wrapped__gives access to the undecorated function, useful in tests. - 29-35A decorator with arguments has three layers:
repeat(times)returnsdecorator, which returnswrapper. - 37-41
@repeat(3)callsrepeat(3)first, then applies the result toping, so calling it returns a list of three strings.
Section 6: Concurrency and the GIL
Q27. What is the GIL? The Global Interpreter Lock is a mutex in the standard CPython build that lets only one thread execute Python bytecode at a time. It simplifies memory management, because reference counts need no per-object locks, but it means pure-Python CPU-bound code does not speed up by adding threads. The GIL is released during blocking I/O and in many C extensions such as NumPy operations, so threads still help for waiting on networks or disks. Recent Python releases have an optional free-threaded build, so a careful answer says that the details depend on the build and version.
Q28. When would you use threads, processes or asyncio? For I/O-bound work with blocking libraries, threads (concurrent.futures.ThreadPoolExecutor) are the simplest. For CPU-bound pure-Python work, use processes (ProcessPoolExecutor or multiprocessing) to get true parallelism at the cost of start-up time and sending data between processes. For very many concurrent network connections with async-aware libraries, asyncio runs thousands of tasks on one thread by switching at each await. Compare them in threading and multiprocessing and async Python.
Q29. If the GIL exists, do I still need locks? Yes. The GIL protects the interpreter's internal data, not your logic. An operation like counter += 1 is several bytecode steps (load, add, store), and a thread switch between them can lose an update. Shared mutable state needs a threading.Lock, a queue or an atomic design. Q30. What is a race condition? A bug whose outcome depends on the timing of operations, such as two workers reading the same balance before either writes it back. The fix is to serialise the critical section, avoid sharing state, or pass messages.
Q31. What is a coroutine, and how does it differ from a generator? A coroutine defined with async def is a function that can pause at await and be resumed by an event loop. It grew out of the same suspension idea as generators, but it is scheduled by the loop rather than driven by next(). Cooperative scheduling means a coroutine that never awaits blocks every other task, which is why a CPU-heavy loop inside async code is a bug. Threads in a browser sandbox are not available, so the demos below simulate the ideas deterministically instead of using real threads.
def increment_steps(shared, name, log):
value = shared["n"]
log.append(f"{name} read {value}")
yield
shared["n"] = value + 1
log.append(f"{name} wrote {value + 1}")
shared = {"n": 0}
log = []
a = increment_steps(shared, "A", log)
b = increment_steps(shared, "B", log)
next(a)
next(b)
for task in (a, b):
try:
next(task)
except StopIteration:
pass
print("\n".join(log))
print("final:", shared["n"], "(expected 2)")
safe = {"n": 0}
for _ in range(2):
task = increment_steps(safe, "S", [])
next(task)
try:
next(task)
except StopIteration:
pass
print("serialised:", safe["n"])A read 0 B read 0 A wrote 1 B wrote 1 final: 1 (expected 2) serialised: 2
Line by line
- 1-6Each 'thread' is a generator that reads the shared number, pauses at
yieldas if the scheduler switched threads, then writes back its stale value plus one. - 8-11One shared dictionary, one log, and two tasks A and B.
- 13-14Run each task up to its pause. Both have now read
0. - 15-19Finish both tasks. A writes 1, then B also writes 1, overwriting A's work.
- 21-22The log shows the interleaving and the final value is 1, not 2: a lost update.
- 24-31Running the tasks one after the other, which is what a lock enforces, gives the correct 2.
from collections import deque
def worker(name, steps):
for i in range(1, steps + 1):
yield f"{name} step {i}"
def run(tasks):
ready = deque(tasks)
order = []
while ready:
task = ready.popleft()
try:
order.append(next(task))
ready.append(task)
except StopIteration:
pass
return order
for line in run([worker("A", 3), worker("B", 2)]):
print(line)A step 1 B step 1 A step 2 B step 2 A step 3
Line by line
- 3-5A task that yields a message at each step. The
yieldis the point where it politely gives control back. - 7-17A tiny event loop: take the next ready task, run it to its next
yield, record the message and put it at the back of the queue. Finished tasks (StopIteration) are dropped. - 19-20Two tasks interleave as A1, B1, A2, B2, A3: this switching at yield points is exactly what asyncio does at
await.
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import threading
def fetch(n):
return n * 2 # imagine a network call here
def crunch(n):
return sum(i * i for i in range(n)) # CPU-bound
counter = 0
lock = threading.Lock()
def safe_add():
global counter
with lock:
counter += 1
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=4) as pool:
print(list(pool.map(fetch, [1, 2, 3])))
with ProcessPoolExecutor() as pool:
print(list(pool.map(crunch, [10_000, 20_000])))Line by line
- 1-2Import the two executors and
threadingfor the lock. - 4-8
fetchstands for I/O-bound work andcrunchfor CPU-bound work. - 10-15A shared counter protected by a lock, so the read-modify-write cannot be interrupted.
- 17-21Threads for I/O-style tasks, processes for CPU-style tasks. The
__main__guard is required for process pools on some platforms.
Section 7: Testing, errors and tooling
Q32. What is the difference between unit, integration and end-to-end tests? A unit test checks one small piece, such as a function, in isolation and runs in milliseconds. An integration test checks that several pieces work together, such as your code and a database. An end-to-end test drives the whole system the way a user would. A healthy suite has many fast unit tests and fewer slow ones above them. The practical details of writing them are in testing with pytest.
Q33. What is EAFP versus LBYL? 'Easier to ask forgiveness than permission' means you try the operation and handle the exception; 'look before you leap' means you check conditions first. Python culture leans towards EAFP because it avoids race conditions between the check and the action (a file can vanish after os.path.exists says it is there) and often reads more simply. LBYL is still right when failure is expensive or the check is trivial and clear. Remember that exceptions are for exceptional paths: catch the narrowest type you can and never use a bare except:. See exceptions.
Q34. How do you test code that calls an external service? Replace the service with a test double so the test is fast and deterministic. unittest.mock.Mock or patch substitutes an object, lets you set return values or side effects, and lets you assert how it was called. Patch the name where it is looked up, not where it is defined. A better design makes the dependency a parameter so you can pass in a fake without patching at all. In pytest, fixtures provide reusable setup and @pytest.mark.parametrize runs one test with many inputs.
Q35. Why use virtual environments, and what is pip freeze for? A virtual environment is an isolated set of installed packages for one project, so project A can use one version of a library while project B uses another without conflict. pip freeze lists installed versions, which you can save to a requirements file so others can reproduce the environment; see virtual environments and pip. Q36. Do type hints change how Python runs? Not by themselves: the interpreter ignores them at run time. Tools such as mypy or pyright read them to catch mistakes before the program runs, and editors use them for completion. See type hints.
data = {"price": "12.50", "qty": "three"}
def lbyl(record, key):
if key in record and record[key].replace(".", "", 1).isdigit():
return float(record[key])
return None
def eafp(record, key):
try:
return float(record[key])
except KeyError:
return "missing"
except ValueError:
return "not a number"
print(lbyl(data, "price"), lbyl(data, "qty"), lbyl(data, "nope"))
print(eafp(data, "price"), eafp(data, "qty"), eafp(data, "nope"))
try:
int("x")
except (ValueError, TypeError) as err:
print(type(err).__name__)
else:
print("no error")
finally:
print("finally always runs")12.5 None None 12.5 not a number missing ValueError finally always runs
Line by line
- 1A record with one good number and one bad string.
- 3-6LBYL: check that the key exists and that the text looks numeric before converting. The checks are easy to get subtly wrong (negative numbers fail here) and every failure collapses into
None. - 8-14EAFP: just try
float(...)and catch the two specific failures, so each failure gets its own clear message. - 16-17Compare both styles on a valid value, a bad value and a missing key.
- 19-25
try/except/else/finally:int("x")raisesValueError, the matching handler prints its name, andfinallyruns whatever happened.
import io
import unittest
from unittest import mock
def price_with_tax(amount, rate):
if amount < 0:
raise ValueError("negative amount")
return round(amount * (1 + rate), 2)
def fetch_rate(country):
raise RuntimeError("would call the network")
def total(amount, country):
return price_with_tax(amount, fetch_rate(country))
class PriceTests(unittest.TestCase):
def test_tax(self):
self.assertEqual(price_with_tax(100, 0.2), 120.0)
def test_negative(self):
with self.assertRaises(ValueError):
price_with_tax(-1, 0.2)
def test_total_uses_rate(self):
with mock.patch(f"{__name__}.fetch_rate", return_value=0.5) as fake:
self.assertEqual(total(10, "PH"), 15.0)
fake.assert_called_once_with("PH")
suite = unittest.defaultTestLoader.loadTestsFromTestCase(PriceTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("failures:", len(result.failures), "errors:", len(result.errors))
print("was successful:", result.wasSuccessful())tests run: 3 failures: 0 errors: 0 was successful: True
Line by line
- 1-3
iolets us capture the runner's report instead of printing it, because the report contains a timing line that changes every run. - 5-8The function under test: pure logic, easy to check.
- 10-14A dependency that would use the network. In a real test we must never call it.
- 16-21
PriceTestsholds three tests. The first checks a value; the second checks that a bad input raises. - 23-26The third replaces
fetch_ratewith a mock that returns0.5, then checks both the answer and how the mock was called.__name__names the current module so the patch targets the right place. - 28-32Load the tests, run them quietly and print counts: three run, none failing.
import pytest
def add(a, b):
return a + b
@pytest.fixture
def numbers():
return [1, 2, 3]
@pytest.mark.parametrize("a, b, expected", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
])
def test_add(a, b, expected):
assert add(a, b) == expected
def test_sum(numbers):
assert sum(numbers) == 6
def test_error():
with pytest.raises(TypeError):
add(1, "x")Line by line
- 1-4Import pytest and define a tiny function to test.
- 6-8A fixture is reusable setup; any test that names
numbersas a parameter receives its return value. - 10-16
parametrizeruns one test three times with different inputs, and each case is reported separately. - 18-19Tests are plain functions with plain
assertstatements; pytest rewrites them to show helpful details when they fail. - 21-23
pytest.raiseschecks that the expected exception happens.
Section 8: Algorithm warm-ups
Most Python screens include one or two short algorithm problems. The goal is rarely a clever trick; it is to show that you can clarify the problem, choose a sensible data structure, handle edge cases and explain the cost. Say your plan aloud before typing, and finish with the time and space complexity. The sorting and searching and LeetCode patterns lessons go much deeper.
Q37. Reverse a string and check for a palindrome. Slicing with s[::-1] reverses a string in one expression. For a palindrome check, normalise first (lower-case, drop non-alphanumeric characters) and compare with the reversed form. Ask whether punctuation and case matter before you start; that question alone shows good habits. Q38. Solve two-sum. Given numbers and a target, return indices of two numbers that add up to it. The brute force checks every pair in O(n squared). The better approach keeps a dictionary of values already seen: for each number, check whether target - number is in the dictionary. That is O(n) time and O(n) space.
Q39. Group words that are anagrams of each other. Two words are anagrams when their sorted letters match, so use the sorted tuple (or string) as a dictionary key and append each word to that key's list. collections.defaultdict(list) keeps it tidy. Q40. Compute Fibonacci numbers efficiently. The naive recursion recomputes the same subproblems and takes exponential time. Memoisation with functools.lru_cache stores each result once, giving linear time; an iterative loop does the same with constant memory. This is the gentlest example of dynamic programming, covered in dynamic programming and in the recursion lesson.
Q41. Implement binary search. On a sorted list, compare the target with the middle element and discard half the range each step, giving O(log n). The usual bugs are off-by-one errors in the bounds and an infinite loop when the window never shrinks, so test with an empty list, one item and a missing target. In real code, bisect from the standard library does this for you. Interviewers also like FizzBuzz as a sanity check; it is about the order of the divisibility tests, with the combined case first.
from collections import defaultdict
def is_palindrome(text):
cleaned = [ch.lower() for ch in text if ch.isalnum()]
return cleaned == cleaned[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"), is_palindrome("python"))
def two_sum(nums, target):
seen = {}
for index, value in enumerate(nums):
need = target - value
if need in seen:
return seen[need], index
seen[value] = index
return None
print(two_sum([2, 7, 11, 15], 9), two_sum([3, 3], 6), two_sum([1, 2], 10))
def group_anagrams(words):
groups = defaultdict(list)
for word in words:
groups["".join(sorted(word))].append(word)
return sorted(sorted(group) for group in groups.values())
print(group_anagrams(["listen", "silent", "enlist", "google", "gogole", "cat"]))
for n in range(1, 16):
if n % 15 == 0:
print("FizzBuzz", end=" ")
elif n % 3 == 0:
print("Fizz", end=" ")
elif n % 5 == 0:
print("Buzz", end=" ")
else:
print(n, end=" ")
print()True False (0, 1) (0, 1) None [['cat'], ['enlist', 'listen', 'silent'], ['gogole', 'google']] 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Line by line
- 3-5Keep only letters and digits in lower case, then compare the list with its reverse.
- 7A famous phrase returns
True, an ordinary word returnsFalse. - 9-16Two-sum with a dictionary of value to index. For each number we ask whether its partner has already been seen; if not we remember this number.
- 18Check the usual case, duplicate values and a no-answer case, which returns
None. - 20-24Sorted letters make a canonical key, so all anagrams of a word land in the same list.
- 26Sort the groups and the words inside them so the printed result is always in the same order.
- 28-36FizzBuzz: test divisibility by 15 first, otherwise the Fizz branch would catch multiples of 15 before FizzBuzz could.
from functools import lru_cache
import bisect
calls = 0
def slow_fib(n):
global calls
calls += 1
return n if n < 2 else slow_fib(n - 1) + slow_fib(n - 2)
slow_fib(15)
print("naive calls:", calls)
fast_calls = 0
@lru_cache(maxsize=None)
def fast_fib(n):
global fast_calls
fast_calls += 1
return n if n < 2 else fast_fib(n - 1) + fast_fib(n - 2)
print(fast_fib(15), "cached calls:", fast_calls)
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
sorted_items = [1, 3, 5, 7, 9, 11]
print(binary_search(sorted_items, 7), binary_search(sorted_items, 4), binary_search([], 1))
print(bisect.bisect_left(sorted_items, 7), bisect.bisect_left(sorted_items, 4))naive calls: 1973 610 cached calls: 16 3 -1 -1 3 2
Line by line
- 1-4Counters let us measure work by counting calls instead of timing, so the output never changes.
- 6-9Naive Fibonacci: each call spawns two more, so the same values are recomputed again and again.
- 11-12Computing the 15th number takes 1973 calls.
- 14-21
lru_cacheremembers results per argument, so each distinctnruns the body once. - 23The 15th Fibonacci number is 610, reached with only 16 calls to the body.
- 25-35Binary search keeps a window
lo..hi, looks at the middle and discards half.-1means not found. - 37-39Found at index 3, missing returns -1, empty list returns -1.
- 40
bisect_leftreturns the insertion point: 3 for an existing 7, and 2 for the missing 4, where it would be inserted.
The calls count and the output of every demo are produced by real runs, so use them as a checking tool: change the input, predict the new counts, then run again.
Common mistakes
β Memorising answers without running them
Reciting 'default arguments are evaluated once' is fine, but interviewers often ask you to predict the output of a snippet. Run each demo, change a value and predict again until the behaviour is obvious rather than remembered.
β Using is to compare values
Writing if x is 5 or if name is 'admin' may appear to work on your machine and fail elsewhere, because identity of numbers and strings is an implementation detail. Use == for values and is only for None and other singletons.
β Claiming the GIL makes threads useless or thread-safe
Both extremes are wrong. Threads help with I/O waits and with C code that releases the lock, and you still need locks for compound operations. Say what workload you are talking about.
β Jumping into code before clarifying the problem
Ask about input size, duplicates, empty input and whether you may modify the data. Then state the plan and the complexity. A correct brute force with a clear improvement path beats a half-finished clever solution.
β Catching exceptions too broadly
A bare except: or except Exception: pass hides bugs, including typos. Catch the narrowest exception, handle it meaningfully and let unexpected errors surface.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What does add_item(1) followed by add_item(2) return the second time, for def add_item(x, bucket=[]): bucket.append(x); return bucket?
Q2. Which statement about is and == is correct?
== calls __eq__ to compare values; is checks object identity and should be reserved for singletons such as None.Q3. What does [f() for f in [lambda: i for i in range(3)]] evaluate to?
i when called, after the loop finished, so all of them see the final value 2. Binding i=i as a default fixes it.Q4. Why use functools.wraps inside a decorator?
__name__ and __doc__, which breaks introspection and debugging output.Q5. Which workload benefits most from ProcessPoolExecutor rather than threads in standard CPython?
Q6. In two-sum, why is a dictionary of seen values better than checking every pair?
Frequently asked questions
How should I prepare for a Python interview in a few weeks?
+Work through one theme per day using this page: read the answers, run each demo and say the explanation out loud. Then solve small problems daily from the practice exercises and review one project of your own so you can talk about real decisions you made.
Do I need to memorise every answer word for word?
+No. Understand the mechanism and explain it in your own words with a tiny example. Interviewers value clear reasoning and honest statements like 'I would check the documentation for that detail' more than perfect recitation.
Which Python version should I assume?
+Assume a currently supported Python 3 release unless told otherwise, and mention version-dependent details, such as the optional free-threaded build or newer syntax, as such. The demos on this page run in Python 3.12.
What if I get a question I cannot answer?
+Say what you do know, reason from first principles and ask a clarifying question. Showing how you would find the answer, for example by running a small experiment or reading the documentation, is a strong response.
Are algorithm questions the main part of a Python interview?
+It depends on the employer. Some focus on language knowledge and code review, others on data-structure problems, and others on a take-home project. Read the job description and ask the recruiter about the stages; the career roadmap has advice on reading listings.
Key takeaways
- βMutable versus immutable and
isversus==explain most beginner-level surprises; demonstrate them with a short snippet. - βDefault arguments are evaluated once and closures capture variables, not values; know the standard fixes.
- β
super()follows the MRO, and shallow copies share inner objects while deep copies do not. - βGenerators are lazy and single-use, and decorators should use
functools.wraps. - βThe GIL limits CPU-bound threads but not I/O waits; pick threads, processes or asyncio by workload and still protect shared state.
- βFor algorithm questions clarify, choose a data structure, test edge cases and state the complexity.