Python Interview Questions and Answers
Last updated 2026-11-19
This page collects the core Python questions that come up in fresher and early-experience interviews: how names and objects work, what mutability means in practice, how scope is resolved, and the handful of famous gotchas that interviewers use to separate memorised definitions from real understanding.
Every answer below is written for current Python 3. Where a question is an output-prediction puzzle, the code is short enough to trace by hand and the output is stated. Try to predict the result before reading the explanation, because that is exactly what you will be asked to do on a whiteboard or a shared editor.
| Level | Fresher to 2 years |
|---|---|
| Focus | Core language semantics |
| Version | Python 3.10 and later |
How interviewers probe Python basics
Most Python screens move quickly from a definition to a small snippet. Expect to be asked what a piece of code prints, why, and how you would fix it. The recurring themes are mutable default arguments, aliasing of lists, closures capturing variables, and the difference between equality and identity.
Answer in two parts: state the rule in one sentence, then name the object or scope involved. Saying that the default list is created once, when the def statement runs, is far stronger than saying it behaves strangely.
Where to go next
Once these are comfortable, move to the subtopic pages: Python OOPs, lists, dicts and sets and decorators. For the round structure and preparation plan, read how to crack a Python interview.
Python Interview Questions and Answers: questions with worked answers
1 Is Python compiled or interpreted?
easyBoth, in the CPython implementation. Source is first compiled to bytecode, which is cached in .pyc files under __pycache__, and then the bytecode is executed by the Python virtual machine. So there is a compile step, but it targets a virtual machine rather than machine code. Other implementations differ: PyPy adds a JIT compiler, and Jython targets the JVM. When an interviewer says Python is interpreted, they mean there is no separate ahead-of-time build step that the programmer runs.
2 What is the difference between mutable and immutable types? Give examples.
easyAn immutable object cannot change its contents after creation: int, float, str, tuple, frozenset, bytes. A mutable object can: list, dict, set, bytearray and most user-defined class instances. The catch is that an immutable container can hold mutable items, so a tuple containing a list can still appear to change. Immutability also matters for hashing: only hashable objects, normally immutable ones, can be dictionary keys or set members.
pythont = (1, [2, 3]) t[1].append(4) print(t) # (1, [2, 3, 4]) t[0] = 9 # TypeError: 'tuple' object does not support item assignment3 What is the mutable default argument problem?
mediumDefault values are evaluated once, when the def statement runs, not on every call. If the default is a list or dict, every call that omits the argument shares that one object, so changes persist between calls. The standard fix is to use None as the default and create a fresh object inside the function body.
pythondef add(x, bucket=[]): bucket.append(x) return bucket print(add(1)) # [1] print(add(2)) # [1, 2] -- same list def add_fixed(x, bucket=None): if bucket is None: bucket = [] bucket.append(x) return bucket4 What is the difference between == and is?
easy== compares values by calling __eq__. is compares identity, meaning whether both names refer to the very same object in memory (the same id()). Use is for singletons such as None, True and False, and == for everything else. Small integers and some short strings may be cached by CPython, so a is b can be True for equal small values, but that is an implementation detail you must never rely on.
pythona = [1, 2] b = [1, 2] print(a == b) # True print(a is b) # False c = a print(c is a) # True5 Is Python pass-by-value or pass-by-reference?
mediumNeither exactly: it is pass-by-object-reference, sometimes called pass-by-assignment. The parameter name is bound to the same object the caller passed. Mutating that object, for example appending to a list, is visible to the caller. Rebinding the parameter to a new object only changes the local name. So the result depends on whether the object is mutable and whether you mutate or rebind.
pythondef f(lst, n): lst.append(1) # mutates caller's list lst = [99] # rebinds local name only n += 1 # int is immutable, rebinds local n data, num = [], 5 f(data, num) print(data, num) # [1] 56 Explain the LEGB rule and the global and nonlocal keywords.
mediumPython looks up a name in this order: Local, Enclosing function, Global (module), Built-in. Assigning to a name anywhere in a function makes it local for the whole function, which causes UnboundLocalError if you read it before assigning. Use global to rebind a module-level name from inside a function, and nonlocal to rebind a variable in the nearest enclosing function. Reading a global needs neither keyword.
pythoncount = 0 def inc(): count += 1 # UnboundLocalError: count is local here def outer(): n = 0 def inner(): nonlocal n n += 1 inner(); inner() return n print(outer()) # 27 What is the difference between a shallow copy and a deep copy?
mediumA shallow copy, made with copy.copy(), list(x), x[:] or x.copy(), creates a new outer container but reuses the same inner objects. A deep copy, copy.deepcopy(), recursively copies everything, so nested objects are independent. With nested mutable data, editing an inner list through a shallow copy changes the original too. Deep copy is slower and handles cycles through a memo dictionary.
pythonimport copy a = [[1, 2], [3]] s = copy.copy(a) d = copy.deepcopy(a) a[0].append(99) print(s) # [[1, 2, 99], [3]] print(d) # [[1, 2], [3]]8 Predict the output: why does a list of lambdas built in a loop all return the same value?
hardClosures capture variables, not values. Every lambda refers to the same variable i in the enclosing scope, and by the time any of them is called the loop has finished with i equal to 2. Bind the current value at definition time with a default argument, or use functools.partial. This late-binding behaviour is one of the most repeated Python interview puzzles.
pythonfs = [lambda: i for i in range(3)] print([f() for f in fs]) # [2, 2, 2] fs = [lambda i=i: i for i in range(3)] print([f() for f in fs]) # [0, 1, 2]9 What is the GIL and how does it affect threads?
mediumThe Global Interpreter Lock is a mutex in CPython that lets only one thread execute Python bytecode at a time. It protects CPython's reference counting and internal structures. Consequences: CPU-bound code gains nothing from threads, while I/O-bound code does, because the lock is released while waiting on sockets or files. For CPU-bound parallelism use multiprocessing or native extensions that release the lock. Recent CPython versions ship an optional free-threaded build, but the default build still has the GIL. See multithreading vs multiprocessing.
10 Predict the output of += on a list versus + for aliases.
mediumFor lists, a += b calls __iadd__, which extends the list in place, so every alias sees the change. a = a + b builds a brand new list and rebinds a, leaving other aliases untouched. For immutable types like tuples and ints, += falls back to creating a new object, so both forms behave the same.
pythona = [1, 2] b = a b += [3] print(a) # [1, 2, 3] a = [1, 2] b = a b = b + [3] print(a, b) # [1, 2] [1, 2, 3]11 What does if __name__ == "__main__" do?
easyWhen a file is run directly, Python sets its __name__ to the string "__main__". When the same file is imported, __name__ is the module's name. The guard lets a file contain reusable functions plus a block that runs only as a script, and it also stops multiprocessing on Windows from re-running top-level code in child processes.
12 How do you create a tuple with one element?
easyYou need a trailing comma: (1,) is a tuple, while (1) is just the integer 1 in parentheses. It is the comma, not the brackets, that makes a tuple, which is why 1, 2 is also a tuple. An empty tuple is written ().
pythonprint(type((1))) # <class 'int'> print(type((1,))) # <class 'tuple'>13 What do and and or return in Python?
mediumThey return one of their operands, not necessarily a bool. a or b returns a if a is truthy, otherwise b. a and b returns a if a is falsy, otherwise b. Both short-circuit, so the right side is not evaluated when the left decides the result. This is used for defaults, but it misfires when a legitimate value like 0 or an empty string is falsy.
pythonprint(0 or "default") # default print("" and "never") # (empty string) print([] or [1] and 5) # 514 What is *args and **kwargs, and what is the order of parameters?
medium*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. The required order is: positional parameters, defaults, *args, keyword-only parameters, **kwargs. A bare / ends positional-only parameters and a bare * starts keyword-only ones. The same symbols unpack at call sites: f(*lst, **d).
pythondef f(a, b=2, *args, c, **kwargs): return a, b, args, c, kwargs print(f(1, 3, 4, 5, c=6, d=7)) # (1, 3, (4, 5), 6, {'d': 7})15 What is the difference between a list comprehension and a generator expression?
mediumA list comprehension [x*x for x in data] builds the full list in memory immediately. A generator expression (x*x for x in data) produces values lazily, one at a time, and can be consumed only once. Use a generator when you only iterate once or the data is large, as in sum(x*x for x in data). Use a list when you need indexing, len() or several passes. More in generators and iterators.
16 Why can a dictionary key not be a list, and what makes an object hashable?
hardDictionary lookup uses hash(key) to find a bucket and then == to confirm. An object is hashable if it has a __hash__ that never changes during its lifetime and equal objects have equal hashes. Lists are mutable and define __eq__ without __hash__, so Python sets __hash__ to None. Tuples are hashable only if all their elements are. A custom class that defines __eq__ must also define __hash__ to be usable as a key.
pythond = {} d[(1, 2)] = "ok" d[[1, 2]] = "bad" # TypeError: unhashable type: 'list' d[(1, [2])] = "bad" # TypeError: unhashable type: 'list'17 What is the output of chained comparison and why?
hardPython chains comparisons: a < b < c means a < b and b < c, with b evaluated once. That also applies to == and is, which produces surprises: 1 == 1 in [1] means (1 == 1) and (1 in [1]). It is handy for range checks like 0 <= x < 10, and a classic trap when someone expects (a < b) < c.
pythonx = 5 print(1 < x < 10) # True print(1 < x > 3) # True print(False == False in [False]) # True
Frequently asked questions
What Python topics are asked most in fresher interviews?
Data types and mutability, list and dict operations, functions and scope, OOP basics, exceptions, generators, decorators and simple coding problems on strings and lists. Service-company tests lean on output prediction, while product companies add data structure problems.
Do I need to know the GIL for a fresher interview?
You should be able to explain it in a few sentences: one thread runs bytecode at a time in CPython, so threads help I/O-bound work but not CPU-bound work, and multiprocessing is the usual workaround.
Should I learn Python 2 differences?
No. Interviews now assume Python 3. You may be asked about the print function or integer division, but only as history.
How should I practise output-prediction questions?
Write the prediction on paper first, run the code afterwards, and then explain the gap in one sentence. Repeat on the same snippet with a small change.
Related guides
More in Programming Language Interview Questions by Language
- Python Lambda, Map, Filter and Reduce Interview Questions
- Python List, Dict and Set Interview Questions
- Python Memory Management Interview Questions
- Python Multithreading and Multiprocessing Interview Questions
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions
- SQL Indexes Interview Questions
- SQL Interview Questions and Answers
- SQL Interview Questions for Freshers
- SQL Joins Interview Questions