Skip to the content.

Python Interview Questions and Answers: Beginner to Advanced, With Code (2027)

A free, practical list of Python interview questions with answers and runnable code, from beginner basics (mutability, lists vs tuples, *args) through intermediate topics (decorators, generators, context managers, closures) to advanced Python (the GIL and free-threading, asyncio, descriptors, metaclasses, memory management). It is written for Python developer, backend, data and machine learning interviews, and every code block in this README is executed by an automated test so the answers stay correct.

Last reviewed: December 2026. Answers target modern Python (3.12 and newer). The latest release at review time is Python 3.15 (released October 2026); version notes like “3.14+” mark when a feature arrived.

Table of contents

How to use this list

Study roadmap

Stage Topics Time Questions
1. Core language Types, mutability, data structures, functions, comprehensions, exceptions 1-2 weeks 1-20
2. Pythonic code Iterators, generators, decorators, context managers, closures, collections, itertools 1-2 weeks 21-40
3. Internals and concurrency Object model, memory, GIL, threads vs processes vs asyncio, descriptors, metaclasses 1-2 weeks 41-55
4. Practice Output prediction and live coding Ongoing Final sections
5. Your domain Web (Django, FastAPI), data (pandas, NumPy), ML (PyTorch), testing (pytest) Depends on role See resources

Beginner questions (1-20)

1. What are Python’s key features? [B]

Python is a high-level, dynamically typed, garbage-collected language with a large standard library. “Dynamically typed” means types belong to objects, not variables; a name can point to any object. It is also strongly typed: "1" + 1 raises TypeError instead of silently converting. CPython, the reference implementation, compiles source to bytecode and runs it on a virtual machine.

2. What is the difference between mutable and immutable types? [B]

Immutable objects can’t change after creation: int, float, bool, str, tuple, frozenset, bytes. Mutable ones can: list, dict, set, bytearray, most user-defined objects.

s = "hi"
t = s
s += "!"          # creates a new string; t still points to the old one
assert t == "hi" and s == "hi!"

a = [1, 2]
b = a
a += [3]          # list += mutates in place; b sees the change
assert b == [1, 2, 3] and a is b

3. List vs tuple: when do you use each? [B]

Lists are mutable sequences for collections that change. Tuples are immutable, slightly smaller and faster to create, and hashable if their contents are hashable, so they can be dictionary keys or set members. Use tuples for fixed records ((lat, lng)) and lists for growing collections.

locations = {(40.7, -74.0): "New York"}   # tuple as a dict key
assert locations[(40.7, -74.0)] == "New York"
try:
    {[1, 2]: "nope"}
except TypeError:
    pass                                   # lists are unhashable

4. What is the difference between is and ==? [B]

== compares values (calls __eq__); is compares identity (same object in memory). Use is only for singletons such as None.

a = [1, 2, 3]
b = [1, 2, 3]
assert a == b and a is not b
x = None
assert x is None

Small integers and some strings are cached by CPython, so is may appear to work for them; never rely on that.

5. How do dictionaries work, and are they ordered? [B]

A dict is a hash table: keys are hashed to find a slot, giving average O(1) lookup, insert and delete. Keys must be hashable. Since Python 3.7, dicts preserve insertion order as a language guarantee.

d = {"b": 1, "a": 2}
d["c"] = 3
assert list(d) == ["b", "a", "c"]
assert d.get("missing", 0) == 0

6. What are *args and **kwargs? [B]

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. The same symbols unpack at call sites.

def describe(name, *args, **kwargs):
    return name, args, kwargs

assert describe("x", 1, 2, debug=True) == ("x", (1, 2), {"debug": True})

def add(a, b, c):
    return a + b + c

nums = [1, 2, 3]
assert add(*nums) == 6
assert add(**{"a": 1, "b": 2, "c": 3}) == 6

7. What are positional-only and keyword-only parameters? [B]

Parameters before / are positional-only; parameters after * are keyword-only.

def f(a, b, /, c, *, d):
    return a + b + c + d

assert f(1, 2, 3, d=4) == 10
assert f(1, 2, c=3, d=4) == 10
try:
    f(a=1, b=2, c=3, d=4)       # a and b are positional-only
except TypeError:
    pass

8. Why are mutable default arguments dangerous? [B]

Default values are evaluated once, when the function is defined, and shared across calls.

def bad_append(item, items=[]):
    items.append(item)
    return items

assert bad_append(1) == [1]
assert bad_append(2) == [1, 2]      # surprise: same list reused

def good_append(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert good_append(1) == [1]
assert good_append(2) == [2]

9. What are list, dict and set comprehensions? [B]

Concise expressions that build collections from iterables, usually clearer and faster than an equivalent loop with append.

squares = [n * n for n in range(5)]
evens = {n for n in range(10) if n % 2 == 0}
lengths = {w: len(w) for w in ["hi", "hello"]}
assert squares == [0, 1, 4, 9, 16]
assert evens == {0, 2, 4, 6, 8}
assert lengths == {"hi": 2, "hello": 5}

Keep them to one or two clauses; nested multi-condition comprehensions are harder to read than a loop.

10. What is slicing? [B]

seq[start:stop:step] returns a new sequence; stop is excluded, negative indices count from the end.

s = "interview"
assert s[0:5] == "inter"
assert s[-4:] == "view"
assert s[::-1] == "weivretni"
assert s[::2] == "itriw"

11. How does exception handling work? [B]

try runs code; except handles specific exceptions; else runs if no exception occurred; finally always runs. Catch the narrowest exception you can, and never use a bare except: that would also swallow KeyboardInterrupt.

def parse(s):
    try:
        value = int(s)
    except ValueError:
        return None
    else:
        return value * 2
    finally:
        pass   # cleanup would go here

assert parse("21") == 42
assert parse("x") is None

Use raise NewError(...) from err to chain exceptions and keep the original cause in the traceback.

12. What is the difference between append and extend? [B]

a = [1, 2]
a.append([3, 4])      # adds one element (a list)
assert a == [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])      # adds each element
assert b == [1, 2, 3, 4]

13. Shallow copy vs deep copy? [B]

A shallow copy creates a new outer container that still references the same inner objects; a deep copy recursively copies everything.

import copy

grid = [[0, 0], [0, 0]]
shallow = copy.copy(grid)
deep = copy.deepcopy(grid)
grid[0][0] = 9
assert shallow[0][0] == 9      # shares inner lists
assert deep[0][0] == 0

Related trap: [[0] * 2] * 2 creates two references to the same inner list. Use [[0] * 2 for _ in range(2)].

14. How do you swap two variables? [B]

a, b = 1, 2
a, b = b, a
assert (a, b) == (2, 1)

The right side builds a tuple, then unpacks it into the targets.

15. What are lambda functions? [B]

Anonymous single-expression functions, handy as short key= arguments. For anything longer, use def.

people = [("Ana", 31), ("Bo", 25)]
assert sorted(people, key=lambda p: p[1]) == [("Bo", 25), ("Ana", 31)]

16. What does if __name__ == "__main__": do? [B]

When a file runs as a script, its __name__ is "__main__"; when it is imported, __name__ is the module name. The guard lets a file be both importable and runnable without executing script code on import.

17. What is the difference between a module and a package? [B]

A module is a single .py file. A package is a directory of modules, usually with an __init__.py (directories without one are “namespace packages”). Imports are cached in sys.modules, so a module’s top-level code runs once per process.

18. How do range, enumerate and zip help write Pythonic loops? [B]

names = ["a", "b", "c"]
scores = [90, 80, 70]
pairs = [(i, n) for i, n in enumerate(names, start=1)]
assert pairs == [(1, "a"), (2, "b"), (3, "c")]
assert dict(zip(names, scores)) == {"a": 90, "b": 80, "c": 70}
try:
    list(zip([1, 2], [1], strict=True))   # 3.10+: detect length mismatch
except ValueError:
    pass

19. What are f-strings? [B]

Formatted string literals evaluate expressions inside braces. The = specifier (3.8+) is great for debugging.

name, total = "Ada", 1234.5
assert f"{name} owes ${total:,.2f}" == "Ada owes $1,234.50"
x = 3
assert f"{x=}" == "x=3"

20. What is the difference between sort() and sorted()? [B]

list.sort() sorts in place and returns None; sorted() accepts any iterable and returns a new list. Both are stable (equal elements keep their order) and use Timsort-derived algorithms, O(n log n).

data = [("b", 2), ("a", 2), ("c", 1)]
by_count = sorted(data, key=lambda t: t[1])
assert by_count == [("c", 1), ("b", 2), ("a", 2)]   # stable: b before a

Intermediate questions (21-40)

21. What is a decorator? Write one. [I]

A decorator is a callable that takes a function and returns a replacement, applied with @. Use functools.wraps to keep the original name and docstring.

import functools

def count_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

@count_calls
def greet(name):
    """Say hi."""
    return f"hi {name}"

greet("a"); greet("b")
assert greet.calls == 2
assert greet.__name__ == "greet" and greet.__doc__ == "Say hi."

22. Write a decorator that takes arguments. [I]

Add one more level: a function that returns a decorator.

import functools

def retry(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last = None
            for _ in range(times):
                try:
                    return func(*args, **kwargs)
                except ValueError as err:
                    last = err
            raise last
        return wrapper
    return decorator

attempts = []

@retry(times=3)
def flaky():
    attempts.append(1)
    if len(attempts) < 3:
        raise ValueError("not yet")
    return "ok"

assert flaky() == "ok" and len(attempts) == 3

23. What is a closure? [I]

A nested function that remembers variables from its enclosing scope even after that scope has finished. Use nonlocal to rebind them.

def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

c = make_counter()
c(); c()
assert c() == 3

24. Explain the late-binding closure trap. [I]

Closures look up variables when called, not when created.

funcs = [lambda: i for i in range(3)]
assert [f() for f in funcs] == [2, 2, 2]

fixed = [lambda i=i: i for i in range(3)]   # bind the current value as a default
assert [f() for f in fixed] == [0, 1, 2]

25. What is the LEGB rule? [I]

Name lookup order: Local, Enclosing functions, Global (module), Built-in. Assigning to a name inside a function makes it local unless declared global or nonlocal, which is why reading then assigning a global in a function raises UnboundLocalError.

x = 10
def f():
    try:
        x += 1          # x is local here because of the assignment
    except UnboundLocalError:
        return "unbound"
assert f() == "unbound"

26. Iterables vs iterators? [I]

An iterable has __iter__ returning an iterator (lists, dicts, files). An iterator has __next__ and raises StopIteration when done; it is also iterable (returns itself). Iterators are single-pass.

nums = [1, 2]
it = iter(nums)
assert next(it) == 1 and next(it) == 2
try:
    next(it)
except StopIteration:
    pass
assert list(it) == []     # exhausted

27. What is a generator and why use one? [I]

A function containing yield returns a generator: an iterator that produces values lazily, keeping its state between calls. Memory use stays constant regardless of how many values are produced.

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

import itertools
assert list(itertools.islice(fib(), 8)) == [0, 1, 1, 2, 3, 5, 8, 13]

total = sum(x * x for x in range(1_000_000))   # generator expression, no big list
assert total == 333332833333500000

28. What does yield from do? [I]

It delegates to a sub-iterator, yielding all its values (and passing send()/throw() through).

def flatten(items):
    for item in items:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

assert list(flatten([1, [2, [3, 4]], 5])) == [1, 2, 3, 4, 5]

29. What is a context manager? Write one two ways. [I]

An object used with with that sets something up and guarantees cleanup via __enter__ / __exit__, even if an exception occurs.

import contextlib

class Timer:
    def __enter__(self):
        self.entered = True
        return self
    def __exit__(self, exc_type, exc, tb):
        self.exited = True
        return False          # don't suppress exceptions

with Timer() as t:
    pass
assert t.entered and t.exited

log = []

@contextlib.contextmanager
def tag(name):
    log.append(f"<{name}>")
    try:
        yield
    finally:
        log.append(f"</{name}>")

with tag("b"):
    log.append("text")
assert log == ["<b>", "text", "</b>"]

30. What are @staticmethod, @classmethod and instance methods? [I]

Instance methods receive the instance (self); class methods receive the class (cls), useful for alternative constructors that work with subclasses; static methods receive neither and are plain functions namespaced in the class.

class Date:
    def __init__(self, y, m, d):
        self.y, self.m, self.d = y, m, d

    @classmethod
    def from_string(cls, s):
        return cls(*map(int, s.split("-")))

    @staticmethod
    def is_leap(year):
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

class MyDate(Date):
    pass

assert isinstance(MyDate.from_string("2026-12-01"), MyDate)
assert Date.is_leap(2024) and not Date.is_leap(1900)

31. What are dunder (magic) methods? [I]

Special methods like __init__, __repr__, __eq__, __len__, __iter__, __add__ that let your objects work with built-in syntax and functions.

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

assert Vector(1, 2) + Vector(3, 4) == Vector(4, 6)
assert repr(Vector(1, 2)) == "Vector(1, 2)"

__repr__ should be unambiguous (for developers); __str__ should be readable (for users). If only __repr__ exists, str() uses it. Defining __eq__ without __hash__ makes instances unhashable.

32. What are dataclasses? [I]

@dataclass generates __init__, __repr__, __eq__ (and optionally ordering, immutability via frozen=True, and __slots__ via slots=True) from type-annotated fields.

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Point:
    x: int
    y: int = 0

@dataclass
class Basket:
    items: list = field(default_factory=list)   # never a mutable literal default

p = Point(1)
assert p == Point(1, 0) and hash(p) == hash(Point(1, 0))
try:
    p.x = 5
except AttributeError:     # FrozenInstanceError is a subclass of AttributeError
    pass
assert Basket().items == [] and Basket().items is not Basket().items

33. How does inheritance and the MRO work? What does super() do? [I]

Python supports multiple inheritance. The method resolution order (MRO) is computed with C3 linearization; super() calls the next class in the MRO, not necessarily the parent, which is what makes cooperative multiple inheritance work.

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()

assert [k.__name__ for k in D.__mro__] == ["D", "B", "C", "A", "object"]
assert D().hello() == ["D", "B", "C", "A"]

34. What is @property? [I]

It turns a method into a managed attribute, letting you add validation or computation without changing the public interface.

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._c

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._c = value

    @property
    def fahrenheit(self):
        return self._c * 9 / 5 + 32

t = Temperature(100)
assert t.fahrenheit == 212
try:
    t.celsius = -300
except ValueError:
    pass

35. Which collections types should you know? [I]

from collections import Counter, defaultdict, deque, namedtuple, OrderedDict

assert Counter("banana").most_common(1) == [("a", 3)]

groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
    groups[word[0]].append(word)
assert groups["a"] == ["apple", "avocado"]

q = deque([1, 2, 3], maxlen=3)
q.append(4)                     # O(1) at both ends; oldest item drops
assert list(q) == [2, 3, 4]

Point = namedtuple("Point", "x y")
assert Point(1, 2).x == 1

od = OrderedDict(a=1, b=2)
od.move_to_end("a")             # still useful for LRU-style ordering
assert list(od) == ["b", "a"]

36. What are some useful itertools and functools tools? [I]

import itertools, functools, operator

assert list(itertools.chain([1, 2], [3])) == [1, 2, 3]
assert list(itertools.combinations("abc", 2)) == [("a", "b"), ("a", "c"), ("b", "c")]
assert list(itertools.accumulate([1, 2, 3])) == [1, 3, 6]
assert [k for k, _ in itertools.groupby("aabbbc")] == ["a", "b", "c"]
assert list(itertools.batched(range(5), 2)) == [(0, 1), (2, 3), (4,)]   # 3.12+
assert functools.reduce(operator.mul, [1, 2, 3, 4]) == 24

@functools.cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
assert fib(80) == 23416728348467685

37. How do you write type hints, and are they enforced? [I]

Type hints document intent and power static checkers (mypy, Pyright) and IDEs; the interpreter does not enforce them at runtime. Modern syntax (3.12+) includes built-in generics, X | None, and the type statement and generic parameters.

def first[T](items: list[T]) -> T | None:      # 3.12+ generic syntax
    return items[0] if items else None

type Pair = tuple[int, int]                     # 3.12+ type alias

def total(p: Pair) -> int:
    return sum(p)

assert first([3, 4]) == 3 and first([]) is None
assert total((1, 2)) == 3
assert first("not a list") == "n"   # no runtime enforcement

38. How do you read and write files safely? [I]

Use with so files close even on error, and pass an explicit encoding. pathlib is the modern way to work with paths.

import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "notes.txt"
    path.write_text("line 1\nline 2\n", encoding="utf-8")
    with path.open(encoding="utf-8") as f:
        lines = [line.rstrip("\n") for line in f]   # streams line by line
    assert lines == ["line 1", "line 2"]

39. What is match (structural pattern matching)? [I]

Added in 3.10, match compares a value against patterns, destructuring sequences, mappings and objects.

def handle(command):
    match command:
        case {"action": "move", "x": int(x), "y": int(y)}:
            return f"move to {x},{y}"
        case ["say", *words]:
            return " ".join(words)
        case None:
            return "nothing"
        case _:
            return "unknown"

assert handle({"action": "move", "x": 1, "y": 2}) == "move to 1,2"
assert handle(["say", "hello", "world"]) == "hello world"
assert handle(42) == "unknown"

40. How do you test Python code? [I]

Use pytest (third-party, the most common) or the built-in unittest. Good answers mention fixtures, parametrized tests, mocking external calls with unittest.mock, and keeping tests fast and independent.

from unittest import mock

def fetch_price(client, symbol):
    return client.get(f"/price/{symbol}")["price"]

client = mock.Mock()
client.get.return_value = {"price": 10}
assert fetch_price(client, "ABC") == 10
client.get.assert_called_once_with("/price/ABC")

Advanced questions (41-55)

41. What is the GIL, and what changed with free-threaded Python? [A]

The Global Interpreter Lock in CPython lets only one thread execute Python bytecode at a time per interpreter. Threads still help for I/O-bound work (the GIL is released while waiting on I/O and in many C extensions), but CPU-bound pure-Python code does not speed up with threads in the standard build.

Since Python 3.13 there is an optional free-threaded build (often installed as python3.13t, python3.14t and so on) with the GIL disabled. PEP 779 made it officially supported in 3.14, and 3.15 adds a stable ABI for free-threaded extensions (PEP 803). The default build still has the GIL. Check at runtime:

import sys
gil_enabled = sys._is_gil_enabled() if hasattr(sys, "_is_gil_enabled") else True
assert gil_enabled in (True, False)

For CPU-bound work today: use multiprocessing / ProcessPoolExecutor, the free-threaded build, vectorized libraries (NumPy) or native extensions.

42. Threads vs processes vs asyncio: when do you use each? [A]

Tool Best for Notes
threading / ThreadPoolExecutor I/O-bound work with blocking libraries Shared memory; need locks; GIL limits CPU parallelism in the default build
multiprocessing / ProcessPoolExecutor CPU-bound work True parallelism; data must be pickled between processes
asyncio Many concurrent I/O tasks (network servers, API fan-out) Single thread, cooperative; every library in the path must be async
concurrent.interpreters (3.14+) Isolated interpreters in one process Newer; see PEP 734
from concurrent.futures import ThreadPoolExecutor

def work(n):
    return n * n

with ThreadPoolExecutor(max_workers=4) as pool:
    assert list(pool.map(work, range(5))) == [0, 1, 4, 9, 16]

43. How does asyncio work? [A]

async def defines a coroutine; await suspends it until the awaited operation completes, letting the event loop run other tasks. Use asyncio.TaskGroup (3.11+) for structured concurrency and asyncio.timeout() for deadlines.

import asyncio

async def fetch(i):
    await asyncio.sleep(0.01)      # stands in for network I/O
    return i * 10

async def main():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(i)) for i in range(3)]
    return [t.result() for t in tasks]

assert asyncio.run(main()) == [0, 10, 20]

Common mistakes: calling blocking code (time.sleep, requests.get) inside a coroutine, which freezes the loop (use asyncio.to_thread or an async library), and forgetting to await a coroutine.

44. How does Python manage memory? [A]

CPython uses reference counting: each object tracks how many references point to it and is freed immediately when the count hits zero. A cyclic garbage collector (gc module) finds and frees reference cycles that counting alone can’t. Small objects come from a specialized allocator (pymalloc).

import gc, sys, weakref

class Node:
    pass

a = Node()
assert sys.getrefcount(a) >= 1      # exact counts are an implementation detail

x, y = Node(), Node()
x.other, y.other = y, x             # a reference cycle
ref = weakref.ref(x)                # weak references don't keep objects alive
del x, y
gc.collect()
assert ref() is None                # the cycle collector freed them

45. What are __slots__? [A]

Declaring __slots__ replaces the per-instance __dict__ with fixed storage, saving memory for many small objects and preventing new attributes.

class P:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x, self.y = x, y

p = P(1, 2)
try:
    p.z = 3
except AttributeError:
    pass
assert not hasattr(p, "__dict__")

46. What is a descriptor? [A]

An object defining __get__, __set__ or __delete__ that controls attribute access when stored on a class. Properties, methods, classmethod and staticmethod are all built on descriptors.

class Positive:
    def __set_name__(self, owner, name):
        self.name = "_" + name
    def __get__(self, obj, objtype=None):
        return getattr(obj, self.name)
    def __set__(self, obj, value):
        if value <= 0:
            raise ValueError("must be positive")
        setattr(obj, self.name, value)

class Order:
    qty = Positive()
    def __init__(self, qty):
        self.qty = qty

assert Order(3).qty == 3
try:
    Order(0)
except ValueError:
    pass

47. What is a metaclass? When would you use one? [A]

A metaclass is the class of a class (type by default); it controls class creation. Real uses: registries, ORMs, enforcing interfaces. Most needs are met more simply by __init_subclass__ or class decorators, which is the answer interviewers like to hear.

class Plugin:
    registry = {}
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry[cls.__name__.lower()] = cls

class Csv(Plugin): pass
class Json(Plugin): pass

assert set(Plugin.registry) == {"csv", "json"}

class Meta(type):
    def __new__(mcls, name, bases, ns):
        ns["created_by_meta"] = True
        return super().__new__(mcls, name, bases, ns)

class Model(metaclass=Meta):
    pass

assert Model.created_by_meta and type(Model) is Meta

48. What are abstract base classes and protocols? [A]

abc.ABC with @abstractmethod prevents instantiating incomplete subclasses (nominal typing). typing.Protocol describes required methods structurally (“duck typing” checked by type checkers), with no inheritance needed.

from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

class Shape(ABC):
    @abstractmethod
    def area(self): ...

try:
    Shape()
except TypeError:
    pass

@runtime_checkable
class HasClose(Protocol):
    def close(self) -> None: ...

class Conn:
    def close(self) -> None:
        pass

assert isinstance(Conn(), HasClose)    # structural check, no inheritance

49. How are Python objects hashed, and what makes a good dict key? [A]

hash() calls __hash__. Objects that compare equal must have equal hashes. Keys should be immutable; if a key’s hash changed after insertion, the dict could no longer find it. String hashes are randomized per process (hash randomization) to resist collision attacks, so don’t persist hash() values.

50. What is the difference between copy, pickle and json serialization concerns? [A]

json is a safe, language-neutral text format for basic types. pickle serializes almost any Python object but executing pickle.loads on untrusted data can run arbitrary code; never unpickle data from untrusted sources. For configs use JSON/TOML (tomllib reads TOML in the standard library since 3.11).

51. How do you profile and speed up Python code? [A]

Measure first: timeit for snippets, cProfile (or, in 3.15+, the new profiling package with its sampling profiler) for whole programs, and memory tools like tracemalloc. Then: better algorithms and data structures (sets for membership), built-ins and comprehensions, avoiding repeated work (functools.cache), vectorized libraries, and only then native code (Cython, Rust via PyO3) or a different runtime.

import timeit
setup = "data = list(range(10_000)); s = set(data)"
t_list = timeit.timeit("9_999 in data", setup=setup, number=200)
t_set = timeit.timeit("9_999 in s", setup=setup, number=200)
assert t_set < t_list   # O(1) average vs O(n)

52. What is the difference between __new__ and __init__? [A]

__new__ creates and returns the instance (a static method that receives the class); __init__ initializes the already-created instance and returns None. Override __new__ for immutable types or to control instance creation (for example caching).

class Upper(str):
    def __new__(cls, value):
        return super().__new__(cls, value.upper())

assert Upper("abc") == "ABC"

53. What does the with statement guarantee with locks, and how do you avoid race conditions with threads? [A]

Even with the GIL, compound operations like counter += 1 are not atomic. Protect shared state with threading.Lock (used as a context manager), or avoid sharing by passing messages through queue.Queue.

import threading

counter = 0
lock = threading.Lock()

def work():
    global counter
    for _ in range(10_000):
        with lock:
            counter += 1

threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
assert counter == 40_000

54. How are virtual environments and packaging done in modern Python? [A]

Create isolated environments with python -m venv .venv (or a tool such as uv, Poetry or Hatch). Declare dependencies in pyproject.toml (PEP 621 metadata), pin exact versions for applications with a lock file, and install with pip or uv. Never install project dependencies into the system Python.

55. What are some security pitfalls in Python? [A]

eval/exec on user input, unpickling untrusted data, yaml.load without a safe loader, SQL built with f-strings (use parameterized queries), subprocess with shell=True and user input, and not pinning dependencies (supply chain risk).

import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users (name TEXT)")
con.execute("INSERT INTO users VALUES ('ann')")
user_input = "ann' OR '1'='1"
rows = con.execute("SELECT * FROM users WHERE name = ?", (user_input,)).fetchall()
assert rows == []      # the parameter is treated as data, not SQL

What’s new in Python 3.13, 3.14 and 3.15

Interviewers at Python-heavy companies increasingly ask what’s new. Highlights from the official “What’s New” pages for 3.13, 3.14 and 3.15:

Version Released Highlights
3.13 October 2024 New interactive shell (REPL) with colors and multi-line editing; experimental free-threaded build (PEP 703); experimental JIT; improved error messages
3.14 October 2025 Deferred evaluation of annotations (PEP 649/749); template strings, t-strings (PEP 750); multiple interpreters in the stdlib (PEP 734); except A, B: without parentheses (PEP 758); Zstandard compression module (PEP 784); free-threaded Python officially supported (PEP 779)
3.15 October 2026 Explicit lazy imports with the lazy keyword (PEP 810); built-in frozendict (PEP 814); UTF-8 as the default encoding (PEP 686); a new profiling package with a sampling profiler (PEP 799); unpacking in comprehensions (PEP 798); stable ABI for free-threaded builds (PEP 803)

Two examples you can run on 3.14+ and 3.15+:

# requires: 3.14
from string.templatelib import Template

name = "world"
t = t"hello {name}"
assert isinstance(t, Template)
assert t.strings == ("hello ", "")
assert t.values == ("world",)
# requires: 3.15
fd = frozendict(x=1, y=2)
assert fd == frozendict(y=2, x=1)
assert hash(fd) == hash(frozendict(x=1, y=2))
try:
    fd["z"] = 3
except TypeError:
    pass

t-strings differ from f-strings: they produce a Template object with the static strings and interpolated values kept separate, so libraries can safely escape values (HTML, SQL, shell) before combining them.

Output prediction questions

Predict the output, then run the block.

# 1. Integer division and modulo with negatives (floor semantics)
assert 7 // 2 == 3
assert -7 // 2 == -4
assert -7 % 2 == 1

# 2. Chained comparison
assert (1 < 2 < 3) is True
assert (1 < 3 > 2) is True

# 3. Truthiness
assert [bool(x) for x in [0, "", [], {}, None, "0", [0]]] == [False, False, False, False, False, True, True]

# 4. String multiplication and join
assert "-".join(["a"] * 3) == "a-a-a"

# 5. Floating point
assert 0.1 + 0.2 != 0.3
import math
assert math.isclose(0.1 + 0.2, 0.3)

# 6. Dict key collisions: True == 1 and hash(True) == hash(1)
assert {True: "a", 1: "b"} == {True: "b"}

# 7. Default argument evaluated once
def f(x=[]):
    x.append(1)
    return len(x)
f()
assert f() == 2

# 8. Rounding uses banker's rounding (round half to even)
assert round(2.5) == 2 and round(3.5) == 4

# 9. List multiplication shares references
grid = [[0] * 2] * 2
grid[0][0] = 1
assert grid == [[1, 0], [1, 0]]

# 10. Generators are consumed once
g = (x for x in range(3))
assert sum(g) == 3 and sum(g) == 0

Live coding exercises

Common short tasks in Python screens, with idiomatic solutions.

# Two Sum: indices of two numbers adding to target, O(n)
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 []

assert two_sum([2, 7, 11, 15], 9) == [0, 1]
# Is a string a palindrome, ignoring case and non-alphanumerics?
def is_palindrome(s):
    cleaned = [c.lower() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

assert is_palindrome("A man, a plan, a canal: Panama")
assert not is_palindrome("race a car")
# Word frequency: top k words
from collections import Counter
import re

def top_words(text, k):
    words = re.findall(r"[a-z']+", text.lower())
    return [w for w, _ in Counter(words).most_common(k)]

assert top_words("the cat and the hat and the bat", 2) == ["the", "and"]
# LRU cache with OrderedDict
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.data = OrderedDict()

    def get(self, key):
        if key not in self.data:
            return -1
        self.data.move_to_end(key)
        return self.data[key]

    def put(self, key, value):
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.capacity:
            self.data.popitem(last=False)

cache = LRUCache(2)
cache.put(1, 1); cache.put(2, 2)
assert cache.get(1) == 1
cache.put(3, 3)            # evicts key 2
assert cache.get(2) == -1
# Flatten a nested dict into dotted keys
def flatten(d, prefix=""):
    out = {}
    for k, v in d.items():
        key = f"{prefix}.{k}" if prefix else k
        if isinstance(v, dict):
            out.update(flatten(v, key))
        else:
            out[key] = v
    return out

assert flatten({"a": 1, "b": {"c": 2, "d": {"e": 3}}}) == {"a": 1, "b.c": 2, "b.d.e": 3}
# Merge overlapping intervals
def merge(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

assert merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
# Read a large file lazily in fixed-size chunks
import io

def chunks(stream, size):
    while block := stream.read(size):
        yield block

assert list(chunks(io.StringIO("abcdefg"), 3)) == ["abc", "def", "g"]
# Rate limiter: allow at most n calls per window (sliding log)
from collections import deque

class RateLimiter:
    def __init__(self, n, window):
        self.n, self.window, self.calls = n, window, deque()

    def allow(self, now):
        while self.calls and now - self.calls[0] >= self.window:
            self.calls.popleft()
        if len(self.calls) < self.n:
            self.calls.append(now)
            return True
        return False

rl = RateLimiter(2, 10)
assert [rl.allow(t) for t in (0, 1, 2, 11)] == [True, True, False, True]

Practice more on LeetCode with Python: Two Sum, Valid Palindrome, Top K Frequent Words, LRU Cache, Merge Intervals.

Best resources

Resource Free/Paid Best for
Official Python tutorial Free The language from the source
Python standard library docs Free collections, itertools, functools, asyncio
Python HOWTOs (descriptors, sorting, logging, free-threading) Free Deep, official explanations
PEP index Free Why features exist
Real Python Many free articles; paid membership Practical tutorials
Think Python, 3rd edition Free online (also sold in print) Beginners
Automate the Boring Stuff with Python Free online (also sold in print) Practical scripting
Python Tutor Free Visualizing references and mutation
Exercism Python track Free Exercises with mentoring
LeetCode Free tier; Premium paid Algorithm practice in Python
Fluent Python, 2nd ed. (O’Reilly) Paid Deep idiomatic Python, the best intermediate-to-advanced book
Effective Python (Addison-Wesley) Paid Concise best practices
mypy docs Free Type hints in practice
pytest docs Free Testing

FAQ

What Python questions are asked in interviews? Core language behavior (mutability, data structures, scoping), Pythonic idioms (comprehensions, generators, decorators, context managers), OOP (dataclasses, inheritance, dunder methods), concurrency (GIL, threads vs processes vs asyncio) and a live coding problem solved in Python.

How do I prepare for a Python interview in a week? Days 1-2: questions 1-20. Days 3-4: 21-40. Day 5: 41-55 and the what’s-new table. Day 6: output prediction and live coding sections, plus five LeetCode problems in Python. Day 7: explain five answers out loud and review mistakes.

Is Python good for coding interviews? Yes. It is concise, has strong built-ins (dict, set, heapq, collections.deque, bisect) and is widely accepted. Know the complexity of built-in operations (for example list.pop(0) is O(n); use deque.popleft()).

Do I need to know Python 3.15 features? Not usually, but knowing the GIL/free-threading story and a couple of recent features signals you follow the language.

What’s the difference between Python 2 and 3? Python 2 reached end of life on January 1, 2020. You may still be asked about it for legacy codebases: print became a function, strings became Unicode by default, integer division changed (/ returns float in 3).

How do I answer questions I don’t know? Say what you do know, reason about it, and suggest how you’d find out (docs, a quick experiment in the REPL). Interviewers value honest reasoning over guessing.

Where to go next

Contributing

Pull requests welcome. Each new question needs a clear answer in your own words and, where useful, a self-contained python code block that uses assert to prove the claim. Mark version-specific blocks with a first line like # requires: 3.14. Run python3 tests/run_readme.py before submitting.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.