Skip to content
Home/Resources/AI & ML/Python interview questions
Interview prep · AI & ML

Python Interview Questions and Answers for 2026: 40 Model Answers With Tested Code

By Younus FardeenUpdated 11 Nov 202621 min read
Short answer

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.

VersionStatus on 11 Nov 2026What interviews mention
3.9End of lifedict | dict, str.removeprefix, functools.cache, list[int] hints
3.10End of lifematch, int | None hints, dataclass(slots=True)
3.11Security fixes to October 2027ExceptionGroup, except*, tomllib, typing.Self
3.12Security fixes to October 2028The type statement, new f-string grammar
3.13Security fixes to October 2029Experimental free-threaded build and JIT
3.14Bugfix releases, support to October 2030Free-threaded build officially supported, deferred annotations, template strings
3.15Released 9 October 2026Lazy 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)))                      # 1

Data types, functions and closures (Q1 to Q11)

  • Q1. What are mutable and immutable objects? Lists, dicts, sets and bytearray change in place. int, float, str, tuple, frozenset and bytes do not, so changing one builds a new object. Appending to a list kept its id, while += on a string did not. Python 3.15 adds an immutable frozendict.
  • 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]), yet t[0] = 9 raised TypeError.
  • Q3. What is the difference between is and ==? == compares values and is compares identity. Two equal lists gave True 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 use is for numbers or strings. Use it for None.
  • Q4. Shallow copy or deep copy? copy.copy copies the outer container only. copy.deepcopy copies nested objects too. After grid[0][0] = 9, the shallow copy showed 9 and the deep copy 0. Slicing and list(x) are shallow.
  • Q5. Why is a mutable default argument dangerous? The tutorial says a default is evaluated only once, when def runs, so a list default is shared between calls: add_item(1), add_item(2) printed [1, 2] [1, 2]. Default to None and 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, and dict | dict merging 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? *args collects extra positional arguments into a tuple. A parameter written with two stars, usually kwargs, 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, global and nonlocal. Names resolve Local, Enclosing, Global, then Built-in. Assigning in a function makes a local unless you declare global, or nonlocal for an enclosing function's variable. Two bump() calls made count 2, 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, and area(width=3, height=4) raised TypeError. They let you change names later without breaking callers.
  • Q11. How does caching with functools work? lru_cache stores results by arguments, and functools.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, so Point(1) printed new then init. Override __new__ when subclassing immutable types such as int or tuple, 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) showed Rs 250, but a list of them showed Money(250), because containers use repr.
  • 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. For D(B, C) it is D, B, C, A, object, so D().hi() returned DBCA.
  • Q16. Explain @property, @classmethod and @staticmethod. @property exposes a method as an attribute. @classmethod receives the class and suits alternative constructors. @staticmethod receives neither and is a plain function in the class namespace. Temp(100).fahrenheit gave 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 to None, so {P(1)} raised unhashable 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 raises StopIteration at the end. A for loop calls iter() once, then next() repeatedly. next(it, "done") supplies a default. An exhausted iterator stays empty.
  • Q19. What is a generator? A function with yield returns a generator that runs only when asked for the next value, so it holds one item at a time. next(g) printed computing 0 and 0. yield from delegates 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_calls means greet = log_calls(greet). Wrap the inner function with functools.wraps, or __name__ and __doc__ are lost: greet.__name__ printed greet.
  • 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_calls wrapped it: one calling greet line, two hi lines.
  • Q22. What is a context manager? with calls __enter__, runs the block and always calls __exit__, even after an exception. Returning a true value from __exit__ would swallow the error. contextlib.contextmanager builds one from a generator. The class printed begin and rollback, and the ValueError still 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, commit

Comprehensions, 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. After next(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 by gc.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 recommend multiprocessing or ProcessPoolExecutor for CPU-bound work. asyncio runs many network tasks with async and await. 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__") was False, and Slim().b = 2 raised AttributeError. 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? except handles an error, else runs only if nothing was raised and finally always runs. Catch specific exceptions, never a bare except:. raise ... from e keeps the cause: parse("x") raised RuntimeError with __cause__ set to the ValueError.
  • Q31. When do you write custom exceptions, and what is an exception group? Subclass Exception for domain errors such as InsufficientFunds, so callers catch them precisely. Python 3.11 added ExceptionGroup and except* for several unrelated errors at once, and asyncio.TaskGroup raises them. Python 3.14 lets you write except A, B: without brackets when there is no as.
# 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 collections types should you know? Counter counts items (most_common(2) gave [('to', 2), ('be', 2)]). defaultdict creates missing values. deque has fast operations at both ends and an optional maxlen, while inserting or popping at the front of a list is O(n).
  • Q33. How do you read and write files? Use pathlib.Path and with so files close on errors, and json.dumps and json.loads to convert dicts. Pass encoding="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") returned abab. Tools such as mypy and editors check them. list[int] works from 3.9, int | None from 3.10, typing.Self from 3.11 and the type statement from 3.12. Python 3.14 evaluates annotations lazily.
  • Q35. Why use dataclasses? @dataclass writes __init__, __repr__ and __eq__ from annotated fields. Use field(default_factory=list) for mutable lists. frozen=True blocks assignment, raising FrozenInstanceError, and adds __hash__. slots=True and kw_only=True need 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? unittest ships with Python: subclass TestCase, use assertEqual and assertRaises. pytest is a third-party tool that allows plain assert, pytest.raises and @pytest.mark.parametrize. I ran only the unittest suite, 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. With fetch_rate patched 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 True

Coding problems (Q38 to Q40)

  • Q38. Solve two sum. Keep a dict of seen values. For each number, check whether target - n is 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 defaultdict key. 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

Continue learning

Explainer

Object-oriented programming explained

Classes, objects and the four pillars, with examples.

Open →
Explainer

HashMap explained

How hashing, buckets and collisions work, with Python, JS and Java.

Open →
Project guide · Python

Python projects

32 Python projects for beginners in 2026, from a guessing game to Flask and FastAPI apps, each with a data source and an upgrade, plus tested starter code.

Open guide →32 ideas