Python interviews test mutability, functions and closures, classes and dunder methods, iterators, generators, decorators, the GIL, error handling, the standard library, typing, testing and short coding problems. These 40 model answers come with tested code, mark the Python version each feature arrived in and state where free-threaded Python stands in 3.13, 3.14 and 3.15.
For students and freshers preparing for Python, data and AI roles. The runnable snippets were executed on Python 3.9.6, so they avoid newer syntax, and the output quoted below is what they printed. Snippets that need 3.10 to 3.12 ran on 3.12.13. Nothing was run on 3.13, 3.14 or 3.15, so statements about those come from docs.python.org, read on 11 November 2026.
In Google Trends India, the latest 8 weeks of Python interview questions sit at about 48% of the same weeks a year earlier, and the term peaks in February at about 1.3 times its yearly average. Give each answer a story from a project: see Python project ideas and Masai's Python projects for beginners.
Which Python version to prepare for
Python 3.15 was released on 9 October 2026. Python 3.9 reached end of life on 31 October 2025 and 3.10 on 1 October 2026, yet interviewers still ask which version a feature needs. Support dates come from the Python Developer's Guide.
| Version | Status on 11 Nov 2026 | What interviews mention |
|---|---|---|
| 3.9 | End of life | dict | dict, str.removeprefix, functools.cache, list[int] hints |
| 3.10 | End of life | match, int | None hints, dataclass(slots=True) |
| 3.11 | Security fixes to October 2027 | ExceptionGroup, except*, tomllib, typing.Self |
| 3.12 | Security fixes to October 2028 | The type statement, new f-string grammar |
| 3.13 | Security fixes to October 2029 | Experimental free-threaded build and JIT |
| 3.14 | Bugfix releases, support to October 2030 | Free-threaded build officially supported, deferred annotations, template strings |
| 3.15 | Released 9 October 2026 | Lazy imports, frozendict, UTF-8 default, unpacking in comprehensions |
These four newer features ran on 3.12.13 and fail on 3.9, so they are not marked as runnable:
from dataclasses import dataclass
# 3.10: the match statement and X | Y in type hints
def describe(value: int | str | None) -> str:
match value:
case None:
return "nothing"
case int() if value > 5:
return "big number"
case int():
return "small number"
case str():
return "text"
print(describe(7), describe(2), describe("hi"), describe(None)) # big number small number text nothing
# 3.10: dataclass options slots and kw_only
@dataclass(slots=True, kw_only=True)
class Job:
title: str
salary: int | None = None
print(Job(title="analyst")) # Job(title='analyst', salary=None)
# 3.11: exception groups and except*
try:
raise ExceptionGroup("batch", [ValueError("a"), KeyError("b")])
except* ValueError as eg:
print("value errors:", len(eg.exceptions))
except* KeyError as eg:
print("key errors:", len(eg.exceptions))
# 3.12: the type statement and generic function syntax
type Pair[T] = tuple[T, T]
def first[T](pair: Pair[T]) -> T:
return pair[0]
print(first((1, 2))) # 1Data types, functions and closures (Q1 to Q11)
- Q1. What are mutable and immutable objects? Lists, dicts, sets and
bytearraychange in place.int,float,str,tuple,frozensetandbytesdo not, so changing one builds a new object. Appending to a list kept itsid, while+=on a string did not. Python 3.15 adds an immutablefrozendict. - Q2. How do a list and a tuple differ? Lists are mutable and tuples are not. A tuple is hashable only if its items are, so tuples can be dict keys. A tuple can still hold a mutable item:
(1, [2, 3])became(1, [2, 3, 4]), yett[0] = 9raisedTypeError. - Q3. What is the difference between
isand==?==compares values andiscompares identity. Two equal lists gaveTrue False. CPython caches small ints, which the C API docs put at -5 to 256 up to 3.14 and -5 to 1024 in 3.15, so never useisfor numbers or strings. Use it forNone. - Q4. Shallow copy or deep copy?
copy.copycopies the outer container only.copy.deepcopycopies nested objects too. Aftergrid[0][0] = 9, the shallow copy showed 9 and the deep copy 0. Slicing andlist(x)are shallow. - Q5. Why is a mutable default argument dangerous? The tutorial says a default is evaluated only once, when
defruns, so a list default is shared between calls:add_item(1), add_item(2)printed[1, 2] [1, 2]. Default toNoneand create the list inside. - Q6. How does a dict work, and what can be a key? Keys must be hashable: a list key raised
unhashable type: 'list'. Python's time-complexity page lists average O(1) lookup, assuming a good hash. Insertion order is guaranteed from 3.7, anddict | dictmerging arrived in 3.9.
import copy
# Q1: mutable and immutable objects
nums = [1, 2]
before = id(nums)
nums.append(3)
print(before == id(nums)) # True: the same list object, changed in place
word = "py"
before = id(word)
word += "thon"
print(before == id(word)) # False: strings are immutable, so a new object was made
# Q2: a tuple can hold a mutable object
t = (1, [2, 3])
t[1].append(4)
print(t) # (1, [2, 3, 4])
try:
t[0] = 9
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
# Q3: equality versus identity
a, b = [1, 2], [1, 2]
print(a == b, a is b) # True False
x, y = int("1000000"), int("1000000")
print(x == y, x is y) # True False
# Q4: shallow and deep copies
grid = [[0, 0], [0, 0]]
shallow, deep = copy.copy(grid), copy.deepcopy(grid)
grid[0][0] = 9
print(shallow[0][0], deep[0][0]) # 9 0
# Q5: the mutable default argument
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
def add_item_fixed(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item(1), add_item(2)) # [1, 2] [1, 2]
print(add_item_fixed(1), add_item_fixed(2)) # [1] [2]
# Q6: dictionary keys must be hashable
try:
{[1, 2]: "x"}
except TypeError as e:
print(e) # unhashable type: 'list'
d = {"b": 1, "a": 2}
print(list(d)) # ['b', 'a']- Q7. How do variable-length parameters work?
*argscollects extra positional arguments into a tuple. A parameter written with two stars, usuallykwargs, collects extra keyword arguments into a dict.show(1, 2, sep="-", end="!")printed(1, 2) {'sep': '-', 'end': '!'}. They suit wrappers and decorators. - Q8. Explain LEGB scope,
globalandnonlocal. Names resolve Local, Enclosing, Global, then Built-in. Assigning in a function makes a local unless you declareglobal, ornonlocalfor an enclosing function's variable. Twobump()calls madecount2, and a closure counter returned 2 on its second call. - Q9. What is the late-binding closure trap? A closure captures the variable, not its value.
[lambda: i for i in range(3)]returned[2, 2, 2]. Bind the value with a default argument,lambda i=i: i, to get[0, 1, 2]. - Q10. What are positional-only and keyword-only parameters? In a parameter list,
/makes earlier parameters positional-only (3.8) and a bare*makes later ones keyword-only.area(3, 4)worked, andarea(width=3, height=4)raisedTypeError. They let you change names later without breaking callers. - Q11. How does caching with
functoolswork?lru_cachestores results by arguments, andfunctools.cache(3.9) is the unbounded form.fib(30)ran its body 31 times instead of the 2,692,537 calls a plain recursive version makes. Arguments must be hashable.
import functools
# Q7: *args and **kwargs
def show(*args, **kwargs):
print(args, kwargs)
show(1, 2, sep="-", end="!") # (1, 2) {'sep': '-', 'end': '!'}
# Q8: scope, global and nonlocal
count = 0
def bump():
global count
count += 1
def make_counter():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
bump(); bump()
print(count) # 2
c = make_counter()
c()
print(c()) # 2
# Q9: closures bind names, not values
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]
# Q10: positional-only (3.8) and keyword-only parameters
def area(width, /, height, *, unit="cm"):
return f"{width * height} {unit}"
print(area(3, 4), area(3, height=4, unit="m")) # 12 cm 12 m
try:
area(width=3, height=4)
except TypeError as e:
print(type(e).__name__) # TypeError
# Q11: caching with functools (cache needs 3.9, lru_cache works everywhere)
@functools.lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(30), fib.cache_info()) # 832040 CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)Classes, iterators, decorators and context managers (Q12 to Q22)
- Q12. Class attribute or instance attribute? A class attribute is shared by all instances and an instance attribute belongs to one object. A mutable class attribute such as
items = []leaked between carts: appending through one showed['pen']in the other. Create mutable state in__init__. - Q13. What is the difference between
__new__and__init__?__new__creates the object and__init__initialises it, soPoint(1)printednewtheninit. Override__new__when subclassing immutable types such asintortuple, or to control instance creation. - Q14.
__repr__or__str__?__repr__is for developers and should be unambiguous.__str__is for readable output and falls back to__repr__.print(m)showedRs 250, but a list of them showedMoney(250), because containers userepr. - Q15. What is the MRO, and what does
super()do? The method resolution order is the lookup sequence across base classes, computed by C3 linearisation.super()follows it, not just the direct parent. ForD(B, C)it is D, B, C, A, object, soD().hi()returnedDBCA. - Q16. Explain
@property,@classmethodand@staticmethod.@propertyexposes a method as an attribute.@classmethodreceives the class and suits alternative constructors.@staticmethodreceives neither and is a plain function in the class namespace.Temp(100).fahrenheitgave 212.0. - Q17. How are
__eq__and__hash__related? Equal objects must hash equally. The data model says a class that defines__eq__without__hash__gets__hash__set toNone, so{P(1)}raisedunhashable type: 'P'. Define both, using immutable fields.dataclass(frozen=True)does it for you.
# Q12: a class attribute is shared by every instance
class Cart:
items = [] # class attribute: one list for all carts
def __init__(self):
self.owner = "asha" # instance attribute: one per cart
a, b = Cart(), Cart()
a.items.append("pen")
print(b.items) # ['pen']
# Q13: __new__ creates the object, then __init__ sets it up
class Point:
def __new__(cls, *args):
print("new")
return super().__new__(cls)
def __init__(self, x):
print("init")
self.x = x
Point(1) # new, then init
# Q14: __repr__ for developers, __str__ for users
class Money:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f"Money({self.amount!r})"
def __str__(self):
return f"Rs {self.amount}"
m = Money(250)
print(m, repr(m), [m]) # Rs 250 Money(250) [Money(250)]
# Q15: method resolution order with super()
class A:
def hi(self): return "A"
class B(A):
def hi(self): return "B" + super().hi()
class C(A):
def hi(self): return "C" + super().hi()
class D(B, C):
def hi(self): return "D" + super().hi()
print(D().hi(), [k.__name__ for k in D.__mro__]) # DBCA ['D', 'B', 'C', 'A', 'object']
# Q16: property, classmethod and staticmethod
class Temp:
def __init__(self, celsius):
self._c = celsius
@property
def fahrenheit(self):
return self._c * 9 / 5 + 32
@classmethod
def from_f(cls, f):
return cls((f - 32) * 5 / 9)
@staticmethod
def is_valid(c):
return c >= -273.15
print(Temp(100).fahrenheit, Temp.from_f(212)._c, Temp.is_valid(-300)) # 212.0 100.0 False
# Q17: defining __eq__ removes the default __hash__
class P:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
try:
{P(1)}
except TypeError as e:
print(e) # unhashable type: 'P'
class Q(P):
def __hash__(self):
return hash(self.x)
print(len({Q(1), Q(1)})) # 1- Q18. What is the iterator protocol? An iterable has
__iter__, which returns an iterator. An iterator has__next__and raisesStopIterationat the end. Aforloop callsiter()once, thennext()repeatedly.next(it, "done")supplies a default. An exhausted iterator stays empty. - Q19. What is a generator? A function with
yieldreturns a generator that runs only when asked for the next value, so it holds one item at a time.next(g)printedcomputing 0and0.yield fromdelegates to another iterable. Use generators for large files and streams. - Q20. How does a decorator work? It is a callable that takes a function and returns a replacement, so
@log_callsmeansgreet = log_calls(greet). Wrap the inner function withfunctools.wraps, or__name__and__doc__are lost:greet.__name__printedgreet. - Q21. How do you write a decorator that takes arguments? Write a function that returns the decorator:
repeat(2)returns the real one. Stacked decorators apply bottom up, so@repeat(2)ran first and@log_callswrapped it: onecalling greetline, twohilines. - Q22. What is a context manager?
withcalls__enter__, runs the block and always calls__exit__, even after an exception. Returning a true value from__exit__would swallow the error.contextlib.contextmanagerbuilds one from a generator. The class printedbeginandrollback, and theValueErrorstill reached the caller.
import functools
from contextlib import contextmanager
# Q18: the iterator protocol
class Countdown:
def __init__(self, n):
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.n == 0:
raise StopIteration
self.n -= 1
return self.n + 1
print(list(Countdown(3))) # [3, 2, 1]
it = iter([10, 20])
print(next(it), next(it), next(it, "done")) # 10 20 done
# Q19: a generator runs only when asked for the next value
def squares(limit):
for i in range(limit):
print("computing", i)
yield i * i
g = squares(3)
print(next(g)) # computing 0, then 0
print(list(g)) # computing 1, computing 2, then [1, 4]
# Q20 and Q21: decorators, with and without arguments
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__, args)
return func(*args, **kwargs)
return wrapper
def repeat(times): # a decorator factory
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return deco
@log_calls
@repeat(2)
def greet(name):
"""Say hello."""
print("hi", name)
greet("Asha") # calling greet ('Asha',), hi Asha, hi Asha
print(greet.__name__, greet.__doc__) # greet Say hello.
# Q22: context managers, as a class and with contextlib
class Tx:
def __enter__(self):
print("begin")
return self
def __exit__(self, exc_type, exc, tb):
print("rollback" if exc_type else "commit")
return False # do not swallow the exception
try:
with Tx():
raise ValueError("bad row")
except ValueError as e:
print("caught", e) # begin, rollback, caught bad row
@contextmanager
def tx():
print("begin")
try:
yield
except Exception:
print("rollback")
raise
else:
print("commit")
with tx():
pass # begin, commitComprehensions, memory, the GIL and free threading (Q23 to Q29)
- Q23. How do comprehensions and generator expressions differ? A comprehension builds a list, set or dict at once. A generator expression uses parentheses and yields lazily, so
sum(n * n for n in nums)needs no list. Afternext(gen)took 0,sum(gen)returned 285. Prefer a plain loop when the logic needs several statements. - Q24. What is the walrus operator?
:=(3.8) assigns inside an expression, so[y for x in data if (y := x * 2) > 10]filters on a value it keeps:[16, 24]. Python 3.15 adds unpacking in comprehensions:[*L for L in lists]flattens one level. I did not run that on 3.15.
nums = range(10)
# Q23: list, set and dict comprehensions and a generator expression
print([n * n for n in nums if n % 2 == 0]) # [0, 4, 16, 36, 64]
print({n % 3 for n in nums}, {w: len(w) for w in ["sql", "python"]}) # {0, 1, 2} {'sql': 3, 'python': 6}
gen = (n * n for n in nums)
print(next(gen), sum(gen)) # 0 285
# Q24: the walrus operator (3.8) keeps a computed value
data = [3, 8, 12]
print([y for x in data if (y := x * 2) > 10]) # [16, 24]- Q25. How does Python manage memory? CPython frees most objects by reference counting and runs a cyclic garbage collector for cycles.
sys.getrefcount(x)is one higher than expected because the argument is a temporary reference: it printed 3 for two names. Two objects pointing at each other were freed only bygc.collect(). - Q26. What is the GIL, and what does it limit? The global interpreter lock lets one thread execute Python bytecode at a time in a standard CPython build. It keeps the object model safe, but CPU-bound threads do not run in parallel. Threads still help while waiting: four 0.2 second sleeps finished in under 0.6 seconds, not 0.8.
- Q27. Threads, processes or
asyncio? The threading docs say it suits I/O-bound tasks, and recommendmultiprocessingorProcessPoolExecutorfor CPU-bound work.asyncioruns many network tasks withasyncandawait. Processes cost memory and need picklable data. - Q28. What is free-threaded Python, and where does it stand? A build with the GIL disabled. Python 3.13 added it as experimental (PEP 703). Python 3.14 made it officially supported but optional (PEP 779), and making it the default is undecided.
sys._is_gil_enabled()reports the state, and an unsafe C extension can re-enable the GIL. Python 3.15 adds a stable ABI for these builds. - Q29. What does
__slots__do? It reserves space for named attributes and stops Python creating a__dict__per instance, saving memory for many small objects and blocking new attributes.hasattr(Slim(), "__dict__")wasFalse, andSlim().b = 2raisedAttributeError.dataclass(slots=True)needs 3.10.
import gc
import sys
import threading
import time
# Q25: reference counting, then the cyclic collector
x = []
y = x
print(sys.getrefcount(x)) # 3: the names x and y, plus the temporary argument
class Node:
pass
gc.disable() # keeps this demo deterministic
a, b = Node(), Node()
a.other, b.other = b, a # a reference cycle
del a, b # the counts never reach zero, so nothing is freed yet
print(gc.collect() > 0) # True: the cyclic collector found and freed the cycle
gc.enable()
# Q26 and Q27: threads overlap while they wait, which is why they suit I/O-bound work
def wait():
time.sleep(0.2)
start = time.perf_counter()
workers = [threading.Thread(target=wait) for _ in range(4)]
for w in workers:
w.start()
for w in workers:
w.join()
print(time.perf_counter() - start < 0.6) # True: the four 0.2 second waits overlapped, finishing in under 0.6 seconds instead of 0.8
# Q28: is the GIL enabled? sys._is_gil_enabled() exists from Python 3.13
print(getattr(sys, "_is_gil_enabled", lambda: True)()) # True on a normal build
# Q29: __slots__ removes the per-instance dictionary
class Plain:
def __init__(self):
self.a = 1
class Slim:
__slots__ = ("a",)
def __init__(self):
self.a = 1
print(hasattr(Plain(), "__dict__"), hasattr(Slim(), "__dict__")) # True False
try:
Slim().b = 2
except AttributeError:
print("AttributeError")Errors, standard library, typing and testing (Q30 to Q37)
- Q30. How do try, except, else and finally differ?
excepthandles an error,elseruns only if nothing was raised andfinallyalways runs. Catch specific exceptions, never a bareexcept:.raise ... from ekeeps the cause:parse("x")raisedRuntimeErrorwith__cause__set to theValueError. - Q31. When do you write custom exceptions, and what is an exception group? Subclass
Exceptionfor domain errors such asInsufficientFunds, so callers catch them precisely. Python 3.11 addedExceptionGroupandexcept*for several unrelated errors at once, andasyncio.TaskGroupraises them. Python 3.14 lets you writeexcept A, B:without brackets when there is noas.
# Q30: try, except, else and finally; raise ... from keeps the cause
def parse(text):
try:
value = int(text)
except ValueError as e:
raise RuntimeError(f"bad input {text!r}") from e
else:
print("parsed ok")
return value
finally:
print("cleanup")
print(parse("42")) # parsed ok, cleanup, 42
try:
parse("x")
except RuntimeError as e:
print(e, "| cause:", repr(e.__cause__))
# cleanup, then: bad input 'x' | cause: ValueError("invalid literal for int() with base 10: 'x'")
# A custom exception carries meaning
class InsufficientFunds(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFunds(f"need {amount - balance} more")
return balance - amount
try:
withdraw(100, 150)
except InsufficientFunds as e:
print(e) # need 50 more- Q32. Which
collectionstypes should you know?Countercounts items (most_common(2)gave[('to', 2), ('be', 2)]).defaultdictcreates missing values.dequehas fast operations at both ends and an optionalmaxlen, while inserting or popping at the front of a list is O(n). - Q33. How do you read and write files? Use
pathlib.Pathandwithso files close on errors, andjson.dumpsandjson.loadsto convert dicts. Passencoding="utf-8": the default was locale-dependent, and 3.15 makes UTF-8 the default.
import json
import tempfile
from collections import Counter, defaultdict, deque
from pathlib import Path
# Q32: collections
words = "to be or not to be".split()
print(Counter(words).most_common(2)) # [('to', 2), ('be', 2)]
groups = defaultdict(list)
for w in words:
groups[len(w)].append(w)
print(dict(groups)) # {2: ['to', 'be', 'or', 'to', 'be'], 3: ['not']}
q = deque([1, 2, 3], maxlen=3)
q.append(4)
print(q) # deque([2, 3, 4], maxlen=3)
# Q33: pathlib and json
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "scores.json"
path.write_text(json.dumps({"asha": 91, "ravi": 78}))
data = json.loads(path.read_text())
print(path.suffix, sorted(data), path.parent == Path(folder)) # .json ['asha', 'ravi'] True- Q34. Does Python enforce type hints? No. The typing docs say the runtime does not enforce annotations, so
double("ab")returnedabab. Tools such as mypy and editors check them.list[int]works from 3.9,int | Nonefrom 3.10,typing.Selffrom 3.11 and thetypestatement from 3.12. Python 3.14 evaluates annotations lazily. - Q35. Why use dataclasses?
@dataclasswrites__init__,__repr__and__eq__from annotated fields. Usefield(default_factory=list)for mutable lists.frozen=Trueblocks assignment, raisingFrozenInstanceError, and adds__hash__.slots=Trueandkw_only=Trueneed 3.10.
from dataclasses import dataclass, field, FrozenInstanceError
from typing import List, Optional
# Q34: hints are not enforced at runtime
def double(n: int) -> int:
return n * 2
print(double("ab")) # abab
# Q35: dataclasses write __init__, __repr__ and __eq__ for you
@dataclass(frozen=True)
class Candidate:
name: str
skills: List[str] = field(default_factory=list)
score: Optional[float] = None
c = Candidate("Asha", ["sql"])
print(c) # Candidate(name='Asha', skills=['sql'], score=None)
print(c == Candidate("Asha", ["sql"])) # True
try:
c.name = "Ravi"
except FrozenInstanceError as e:
print(type(e).__name__) # FrozenInstanceError- Q36. unittest or pytest?
unittestships with Python: subclassTestCase, useassertEqualandassertRaises. pytest is a third-party tool that allows plainassert,pytest.raisesand@pytest.mark.parametrize. I ran only theunittestsuite, which passed all 4 tests. - Q37. How do you test code that calls an API? Replace the call: pass the dependency in, or use
unittest.mock.patch. Withfetch_ratepatched to a made-up 84,price_in_inr(2)returned 168 without any network. Keep tests independent and repeatable.
import io
import unittest
from unittest import mock
def total(prices):
return sum(prices)
def fetch_rate():
raise RuntimeError("network call") # a real version would call an API
def price_in_inr(usd):
return usd * fetch_rate()
class TotalTests(unittest.TestCase):
def test_total(self):
self.assertEqual(total([1, 2, 3]), 6)
def test_empty(self):
self.assertEqual(total([]), 0)
def test_bad_input(self):
with self.assertRaises(TypeError):
total(None)
def test_price_with_mock(self):
with mock.patch(__name__ + ".fetch_rate", return_value=84):
self.assertEqual(price_in_inr(2), 168)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(TotalTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(result.testsRun, result.wasSuccessful()) # 4 TrueCoding problems (Q38 to Q40)
- Q38. Solve two sum. Keep a dict of seen values. For each number, check whether
target - nis already there: one pass, O(n) time.two_sum([2, 7, 11, 15], 9)returned(0, 1). The brute-force pair loop is O(n squared), so say why you moved on. - Q39. Group anagrams. Words that sort to the same letters are anagrams, so use the sorted string as a
defaultdictkey. The six-word example gave[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]. Cost is O(n k log k) for n words of length k. - Q40. Flatten a nested list. Recurse with a generator and
yield from, so no intermediate lists are built.flatten([1, [2, [3, 4]], 5])yielded 1 to 5 in order. Very deep nesting can hit the recursion limit, so mention an explicit stack.
from collections import defaultdict
# Q38: two sum in one pass with a dictionary, O(n) time
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target - n], i
seen[n] = i
return None
print(two_sum([2, 7, 11, 15], 9)) # (0, 1)
# Q39: group anagrams by their sorted letters
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
# Q40: flatten a nested list of any depth with a generator
def flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]How to practise these answers
No company publishes a Python rubric, so this advice is ours. Predict each snippet's output before you run it, then change one line and predict again. Back the answers with data structures and algorithms practice on a site from coding practice websites, and read object-oriented programming explained and hashmap explained for Q12 to Q17 and Q6.
Frequently asked questions
What are the most asked Python interview questions?
No company publishes its question bank, so this is our reading. Expect mutability, the mutable default argument, is versus ==, decorators, generators, the GIL, dunder methods and a short coding problem such as two sum. Questions 1, 5, 9, 20, 26 and 38 are the ones to master first.
Is the GIL removed in Python 3.14?
No. Python 3.14 made the free-threaded build, where the GIL is disabled, officially supported but still optional (PEP 779). Python 3.13 introduced it as experimental. Whether free threading becomes the default build is undecided, so most code still runs with the GIL.
Which Python version should I learn on in 2026?
Use a supported version. On 11 November 2026 that means 3.11 to 3.15, with 3.15 the newest, released on 9 October 2026. Python 3.9 and 3.10 are end of life. Learn on 3.12 or later, and know which version introduced match, X | Y hints and except*.
What is the difference between a list and a tuple?
A list is mutable and a tuple is not, so a tuple can be a dict key if its items are hashable. Tuples suit fixed records such as coordinates, lists suit collections that grow. A tuple holding a list can still change inside.
How should a fresher prepare for a Python interview?
Run every snippet, change it and predict the output first. Then build one small project and explain its design choices, and solve dictionary, string and list problems like Q38 to Q40. Say each answer aloud in under a minute.
Do Python interviews include coding rounds?
Many do, but we found no published statistics. Prepare short problems on lists, dicts, sets and strings, then data structures and algorithms. State the complexity and test edge cases such as an empty list.
Sources checked
- Supported and end-of-life Python versions
- Python 3.15 released 9 October 2026: frozendict, lazy imports, UTF-8, unpacking in comprehensions
- PEP 779 free-threaded Python officially supported; t-strings; deferred annotations; except without brackets
- Experimental free-threaded mode and JIT
- Free-threading HOWTO
- PEP 779 phases
- type statement, f-string grammar
- ExceptionGroup, except*, tomllib, Self
- match, X | Y, dataclass slots and kw_only
- dict merge, removeprefix, generic aliases
- __hash__ set to None when __eq__ is defined; __slots__
- Default value evaluated only once
- Small int cache range
- Threading suits I/O-bound tasks
- Built-in type time complexity
- Runtime does not enforce annotations
- pytest plain assert and pytest.raises
Learn this with mentors
AI and machine learning programmes with admissions open: live classes, mentors and project work.

