Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

Python

Interview questions & answers

Readable syntax, stdlib, async, data & web stacks.

102 questions

  1. Question 1

    What is Python?

    A high-level, interpreted language emphasizing readability. Used for web, data, scripting, automation, and ML; large standard library and strong third-party ecosystem (PyPI).

    Example code

    print("hello, world")
  2. Question 2

    Python 2 vs Python 3?

    Python 2 reached end of life in 2020. Python 3 has str/bytes separation, print function, better Unicode, and ongoing features—always target 3.x for new code.

    Example code

    # Python 3 only — 2 is EOL
    print("3.x")
  3. Question 3

    Is Python compiled or interpreted?

    Source is compiled to bytecode (.pyc) then executed by the CPython VM—'interpreted' in practice with a compile step; other implementations (PyPy, GraalPy) differ.

    Example code

    import py_compile
    # .py → bytecode .pyc
  4. Question 4

    Why does indentation matter?

    Blocks are defined by indentation, not braces—enforces readable structure; mix tabs/spaces inconsistently and you get IndentationError.

    Example code

    if True:
        print("indented block")
  5. Question 5

    Dynamic typing in Python?

    Names refer to objects; types are checked at runtime unless you use type checkers (mypy). Variables are not declared with static types by default.

    Example code

    x = 42
    x = "dynamic"
  6. Question 6

    Mutable vs immutable types?

    Immutable: int, float, str, tuple, frozenset—safe as dict keys when contents are hashable. Mutable: list, dict, set—aliasing shares the same object.

    Example code

    a = []
    b = a
    b.append(1)
    assert a == [1]
  7. Question 7

    == vs is?

    == compares value (calls __eq__). is compares object identity (same memory). Use is only for None and small integers in CPython is an implementation detail—prefer == for values.

    Example code

    assert [1] == [1]
    assert [1] is not [1]
  8. Question 8

    What is None?

    Singleton representing absence of value; falsy. Use `x is None`, not `x == None`.

    Example code

    x = None
    assert x is None
  9. Question 9

    Lists vs tuples?

    Lists are mutable, dynamic arrays. Tuples are immutable sequences—often used for fixed records and as dict keys when hashable.

    Example code

    t = (1, 2)
    L = [1, 2]
  10. Question 10

    What is a dict?

    Hash map: keys must be hashable (immutable-ish rule); insertion ordered since 3.7. O(1) average get/set.

    Example code

    d = {"k": 1}
    assert d["k"] == 1
  11. Question 11

    What is a set?

    Unordered collection of unique hashable elements—fast membership and set algebra ops.

    Example code

    s = {1, 2, 2}
    assert len(s) == 2
  12. Question 12

    List comprehensions?

    Concise loops: [expr for x in it if cond]. Prefer over map/filter for readability in Pythonic style.

    Example code

    [n * 2 for n in range(4) if n % 2]
  13. Question 13

    Generators and yield?

    Generator functions pause with yield, resuming on next(); memory-friendly iteration over large streams.

    Example code

    def gen():
        yield 1
        yield 2
    list(gen())
  14. Question 14

    What are *args and **kwargs?

    Collect extra positional (*args tuple) and keyword (**kwargs dict) arguments—common in decorators and wrappers.

    Example code

    def f(*args, **kwargs):
        return args, kwargs
    f(1, a=2)
  15. Question 15

    What is a decorator?

    A callable that takes a function/class and returns a replacement—@syntax applies functools.wraps for metadata preservation.

    Example code

    def deco(fn):
        return lambda: fn() + 1
    @deco
    def g(): return 1
    g()
  16. Question 16

    Context managers and with?

    with obj: calls obj.__enter__ and guarantees obj.__exit__ on leave—files, locks, transactions. contextlib.contextmanager for yield-based CM.

    Example code

    from contextlib import nullcontext
    with nullcontext():
        pass
  17. Question 17

    __init__ and self?

    __init__ initializes instance after __new__; self is the instance passed explicitly—convention, not a keyword.

    Example code

    class A:
        def __init__(self, x):
            self.x = x
  18. Question 18

    How does inheritance work?

    class Child(Parent): ...; super() resolves MRO (method resolution order) for cooperative multiple inheritance.

    Example code

    class B(A):
        pass
  19. Question 19

    __str__ vs __repr__?

    __repr__ should be unambiguous, ideally eval-like; __str__ for human display. print uses __str__, repr() uses __repr__.

    Example code

    class C:
        def __repr__(self): return "C()"
        def __str__(self): return "c"
  20. Question 20

    Modules and packages?

    A module is a .py file; a package is a directory with __init__.py (optional in namespace packages). import resolves via sys.path.

    Example code

    import sys
    sys.path[:2]
  21. Question 21

    What does if __name__ == "__main__" do?

    Code under that guard runs only when the file is executed as a script, not when imported as a module.

    Example code

    if __name__ == "__main__":
        print("script")
  22. Question 22

    What is pip?

    Installer for PyPI packages: pip install, requirements files, virtual environments pair with it.

    Example code

    # pip install requests
  23. Question 23

    venv and virtual environments?

    Isolated site-packages per project—python -m venv .venv; activate to avoid polluting global Python.

    Example code

    # python -m venv .venv
  24. Question 24

    What is requirements.txt?

    Pinned or ranged dependencies for reproducible installs—pip install -r requirements.txt in CI and deploys.

    Example code

    # pip install -r requirements.txt
  25. Question 25

    What are type hints (PEP 484)?

    Optional annotations def f(x: int) -> str: help IDEs and mypy; not enforced at runtime without external tools.

    Example code

    def f(x: int) -> str:
        return str(x)
  26. Question 26

    What are dataclasses?

    @dataclass generates __init__, __repr__, __eq__ for simple data holders—less boilerplate than manual classes.

    Example code

    from dataclasses import dataclass
    @dataclass
    class P:
        n: int
  27. Question 27

    What is enum.Enum?

    Symbolic names grouped: class Color(Enum): RED = 1—compare with is or == per style; good for finite states.

    Example code

    from enum import Enum
    class Color(Enum):
        RED = 1
  28. Question 28

    What is pathlib?

    Object-oriented paths: Path('a') / 'b'—prefer over os.path for readability in 3.4+.

    Example code

    from pathlib import Path
    Path("a") / "b"
  29. Question 29

    try / except / finally / else?

    except catches types; else runs if no exception; finally always runs—order matters for resource cleanup.

    Example code

    try:
        1 / 0
    except ZeroDivisionError:
        pass
    else:
        pass
    finally:
        pass
  30. Question 30

    How do you raise exceptions?

    raise ValueError('msg') or raise from err to chain—bare raise re-raises current exception.

    Example code

    raise ValueError("msg") from None
  31. Question 31

    What is the GIL?

    Global Interpreter Lock allows one thread to execute Python bytecode at a time in CPython—I/O-bound threading can still help; CPU-bound needs multiprocessing or native extensions.

    Example code

    import sys
    # CPython GIL: one bytecode thread at a time
  32. Question 32

    threading vs multiprocessing?

    Threads share memory (GIL limits CPU parallelism). Processes have separate memory—better for CPU-heavy work on CPython.

    Example code

    import threading
    import multiprocessing
  33. Question 33

    What is asyncio?

    Single-threaded cooperative multitasking with event loop—async def, await, non-blocking I/O for many connections.

    Example code

    import asyncio
    asyncio.run(asyncio.sleep(0))
  34. Question 34

    async and await?

    async def defines a coroutine; await suspends until Future completes—run with asyncio.run(main()).

    Example code

    import asyncio
    async def main():
        await asyncio.sleep(0)
    asyncio.run(main())
  35. Question 35

    Lambda functions?

    Anonymous one-expression functions: lambda x: x+1—limited to expressions; prefer named defs for clarity.

    Example code

    (lambda x: x + 1)(2)
  36. Question 36

    map, filter, zip?

    Functional builtins; list comprehensions often clearer. zip pairs iterables; itertools extends patterns.

    Example code

    list(zip("ab", [1, 2]))
  37. Question 37

    Reading and writing files?

    with open(path, 'r', encoding='utf-8') as f: data = f.read()—always specify encoding for text.

    Example code

    with open("f.txt", "w", encoding="utf-8") as f:
        f.write("hi")
  38. Question 38

    JSON in Python?

    json.loads/dumps—use default= for custom types; beware float precision vs JSON numbers.

    Example code

    import json
    json.loads("{}")
  39. Question 39

    What is Django basics (Python)?

    MTV/MVC-style full-stack framework: ORM, admin, migrations, templates—batteries included for CRUD web apps.

    Example code

    from django.http import HttpResponse
    HttpResponse("ok")
  40. Question 40

    What is Flask (Python)?

    Microframework: WSGI app, blueprints, Jinja2—minimal core; extensions add DB, forms, auth.

    Example code

    from flask import Flask
    app = Flask(__name__)
    @app.get("/")
    def hi(): return "hi"
  41. Question 41

    What is FastAPI (Python)?

    ASGI framework with automatic OpenAPI, Pydantic validation, async routes—popular for APIs and microservices.

    Example code

    from fastapi import FastAPI
    app = FastAPI()
    @app.get("/")
    def r(): return {"ok": True}
  42. Question 42

    What is WSGI vs ASGI (Python)?

    WSGI is synchronous request/response; ASGI supports async, WebSockets, long-lived connections—Uvicorn/Hypercorn serve ASGI.

    Example code

    # WSGI: def app(environ, start_response):
    # ASGI: async def app(scope, receive, send):
  43. Question 43

    What is Pydantic (Python)?

    Data validation via models—used by FastAPI; v2 uses core Rust validation for speed.

    Example code

    from pydantic import BaseModel
    class M(BaseModel):
        x: int
  44. Question 44

    What is SQLAlchemy (Python)?

    ORM and SQL toolkit: Session, declarative models, Core for raw SQL—migrations often with Alembic.

    Example code

    from sqlalchemy.orm import declarative_base
    Base = declarative_base()
  45. Question 45

    What is Alembic (Python)?

    Database migration tool for SQLAlchemy—autogenerate from model diffs with review.

    Example code

    # alembic revision --autogenerate
  46. Question 46

    What is Celery (Python)?

    Distributed task queue—brokers Redis/RabbitMQ; workers process async jobs and schedules.

    Example code

    from celery import Celery
    app = Celery("t")
  47. Question 47

    What is Redis (Python)?

    In-memory cache, pub/sub, Celery broker—redis-py or asyncio clients; watch connection pools.

    Example code

    import redis
    r = redis.Redis()
  48. Question 48

    What is pytest (Python)?

    Test framework with fixtures, parametrize, plugins—pytest -q, conftest.py for shared setup.

    Example code

    def test_add():
        assert 1 + 1 == 2
  49. Question 49

    What is unittest (Python)?

    stdlib xUnit style—TestCase, assert methods; still used in older codebases.

    Example code

    import unittest
    class T(unittest.TestCase):
        def test_x(self):
            self.assertEqual(1, 1)
  50. Question 50

    What is Black and Ruff (Python)?

    Black formats opinionated; Ruff lints extremely fast (Rust)—common pre-commit pair.

    Example code

    # black .
    # ruff check .
  51. Question 51

    What is mypy (Python)?

    Static type checker—gradual typing; strictness flags catch real bugs before runtime.

    Example code

    # mypy .
  52. Question 52

    What is Poetry (Python)?

    Project.toml dependencies, virtualenv, publish—alternative to pip+requirements for packaging.

    Example code

    # poetry add requests
  53. Question 53

    What is setuptools (Python)?

    Build wheels/sdists; pyproject.toml with PEP 517 build backend—core of packaging story.

    Example code

    # pyproject.toml [build-system]
  54. Question 54

    What is pip-tools (Python)?

    pip-compile locks transitive deps—reproducible requirements.in → requirements.txt.

    Example code

    # pip-compile requirements.in
  55. Question 55

    What is virtualenvwrapper (Python)?

    Shell helpers around virtualenv—workon, mkvirtualenv for many projects.

    Example code

    # mkvirtualenv myproj
  56. Question 56

    What is f-strings (Python)?

    Formatted string literals: f"{x=}" for debug-style; fastest string formatting in 3.6+.

    Example code

    x = 3
    f"{x=} {x+1=}"
  57. Question 57

    What is walrus operator (Python)?

    := assigns in expressions: while (line := f.readline()): ...—use sparingly for clarity.

    Example code

    n = (y := 5) + 1
    assert n == 6 and y == 5
  58. Question 58

    What is match case (Python)?

    Structural pattern matching (3.10)—match obj: case Point(x,y): ...; powerful for parsers.

    Example code

    match (1, 2):
        case (a, b):
            print(a + b)
  59. Question 59

    What is itertools (Python)?

    count, cycle, chain, groupby, permutations—avoid manual index loops.

    Example code

    import itertools
    list(itertools.pairwise([1, 2, 3]))
  60. Question 60

    What is functools (Python)?

    partial, lru_cache, singledispatch, wraps—composition and memoization utilities.

    Example code

    import functools
    @functools.lru_cache
    def fib(n): return n if n < 2 else fib(n-1)+fib(n-2)
  61. Question 61

    What is operator (Python)?

    itemgetter, attrgetter for sort keys—faster than lambdas in hot paths.

    Example code

    import operator
    operator.add(1, 2)
  62. Question 62

    What is collections (Python)?

    defaultdict, Counter, deque, namedtuple—specialized structures over raw dict/list.

    Example code

    from collections import Counter
    Counter("aba")
  63. Question 63

    What is heapq module (Python)?

    Min-heap queue—heapq.heappush/pop; nlargest/nsmallest for top-k.

    Example code

    import heapq
    h = []
    heapq.heappush(h, 3)
  64. Question 64

    What is bisect (Python)?

    Binary search on sorted lists—bisect_left for insertion points.

    Example code

    import bisect
    bisect.bisect_left([1,3,5], 4)
  65. Question 65

    What is copy (Python)?

    copy.copy shallow; copy.deepcopy for nested graphs—watch cycles and performance.

    Example code

    import copy
    copy.deepcopy({"a": [1]})
  66. Question 66

    What is pickle (Python)?

    Binary serialization of Python objects—not secure against untrusted data; prefer JSON/protobuf for APIs.

    Example code

    import pickle
    pickle.dumps({"a": 1})
  67. Question 67

    What is ctypes (Python)?

    FFI to C shared libraries—struct layout and calling conventions are expert territory.

    Example code

    import ctypes
    ctypes.c_int(42)
  68. Question 68

    What is Cython / mypyc (Python)?

    Compile Python-like or annotated code to C extensions—speed hot loops.

    Example code

    # cythonize or mypyc for compiled extensions
  69. Question 69

    What is PyPy (Python)?

    JIT interpreter—often faster for pure Python; extension compatibility differs from CPython.

    Example code

    # pypy3 script.py
  70. Question 70

    What is GIL workarounds (Python)?

    multiprocessing, native extensions releasing GIL, or asyncio for I/O-bound concurrency.

    Example code

    import multiprocessing as mp
    mp.Pool
  71. Question 71

    What is Queue (Python)?

    queue.Queue thread-safe; asyncio.Queue for coroutines—coordinate producers/consumers.

    Example code

    import queue
    queue.Queue()
  72. Question 72

    What is concurrent (Python)?

    futures.ThreadPoolExecutor / ProcessPoolExecutor—high-level parallel map patterns.

    Example code

    from concurrent.futures import ThreadPoolExecutor
    ThreadPoolExecutor
  73. Question 73

    What is subprocess (Python)?

    Run external processes—capture_output, timeouts, avoid shell=True with user input.

    Example code

    import subprocess
    subprocess.run(["echo", "hi"], capture_output=True)
  74. Question 74

    What is logging (Python)?

    Logger hierarchy, handlers, formatters—prefer over print in services; loguru optional sugar.

    Example code

    import logging
    logging.getLogger(__name__).info("msg")
  75. Question 75

    What is tomllib (Python)?

    3.11+ stdlib TOML reader—for pyproject.toml; tomli on older versions.

    Example code

    import tomllib
    # tomllib.loads(b"[a]\nb=1")  # 3.11+
  76. Question 76

    What is zoneinfo (Python)?

    IANA time zones from stdlib—replace pytz for many use cases in 3.9+.

    Example code

    from zoneinfo import ZoneInfo
    ZoneInfo("UTC")
  77. Question 77

    What is asyncio (Python)?

    create_task, gather, wait_for, Semaphore—backpressure and cancellation discipline.

    Example code

    await asyncio.gather(asyncio.sleep(0), asyncio.sleep(0))
  78. Question 78

    What is aiohttp (Python)?

    Async HTTP client/server—ClientSession reuse; mind connector limits.

    Example code

    # pip install aiohttp
    # ClientSession().get(url)
  79. Question 79

    What is httpx (Python)?

    Sync and async HTTP—HTTP/2, similar API to requests for migration.

    Example code

    # pip install httpx
    # httpx.get("https://example.com")
  80. Question 80

    What is requests (Python)?

    Sync HTTP for scripts—Session for connection pooling; timeouts mandatory in production.

    Example code

    import requests
    requests.get("https://example.com", timeout=5)
  81. Question 81

    What is BeautifulSoup (Python)?

    HTML/XML parsing—lxml backend faster; mind encoding and malformed markup.

    Example code

    # pip install beautifulsoup4
    # BeautifulSoup(html, "html.parser")
  82. Question 82

    What is lxml (Python)?

    Fast XML/HTML; XPath—C dependencies in wheels.

    Example code

    # pip install lxml
    # etree.fromstring(xml)
  83. Question 83

    What is NumPy (Python)?

    Ndarrays, vectorized math—foundation of scientific Python; avoid Python loops on large arrays.

    Example code

    import numpy as np
    np.array([1, 2, 3]) * 2
  84. Question 84

    What is pandas (Python)?

    DataFrame/Series—groupby, merge, time series; watch copy vs view semantics.

    Example code

    import pandas as pd
    pd.Series([1, 2, 3])
  85. Question 85

    What is scikit (Python)?

    Classic ML estimators—fit/predict API; pipelines for preprocessing.

    Example code

    from sklearn.pipeline import Pipeline
    Pipeline
  86. Question 86

    What is Jupyter (Python)?

    Notebooks for exploration—not a deployment target; secrets and long jobs need care.

    Example code

    # jupyter lab
  87. Question 87

    What is matplotlib (Python)?

    Plotting—pyplot state machine vs OOP API; non-interactive backends in servers.

    Example code

    import matplotlib.pyplot as plt
    plt.plot([1, 2, 3])
  88. Question 88

    What is TensorFlow (Python)?

    Graph and eager execution—Keras high-level API; GPU via CUDA/cuDNN stacks.

    Example code

    import tensorflow as tf
    tf.constant(1)
  89. Question 89

    What is PyTorch (Python)?

    Dynamic graphs popular in research—torch.nn, DataLoader patterns.

    Example code

    import torch
    torch.tensor([1.0, 2.0])
  90. Question 90

    What is Django (Python)?

    ORM, migrations, admin, auth, signals—'batteries included' tradeoff vs microframeworks.

    Example code

    from django.db import models
    class M(models.Model):
        name = models.CharField(max_length=80)
  91. Question 91

    What is Django ORM (Python)?

    QuerySet lazy until evaluated; select_related/prefetch_related kill N+1 queries.

    Example code

    Model.objects.select_related("fk").prefetch_related("m2m")
  92. Question 92

    What is Django REST Framework (Python)?

    Serializers, viewsets, routers—permission classes and throttling for APIs.

    Example code

    from rest_framework import serializers
    serializers.ModelSerializer
  93. Question 93

    What is Gunicorn (Python)?

    Pre-fork WSGI HTTP server—workers tune CPU; behind nginx for static and buffering.

    Example code

    # gunicorn app:app
  94. Question 94

    What is Uvicorn (Python)?

    ASGI server for FastAPI/Starlette—--workers for processes, not threads for async.

    Example code

    # uvicorn main:app
  95. Question 95

    What is nginx (Python)?

    Reverse proxy, TLS termination, static files—pass to upstream app servers.

    Example code

    # proxy_pass http://127.0.0.1:8000;
  96. Question 96

    What is Docker (Python)?

    Multi-stage builds slim images; non-root user; pin base image digests in production.

    Example code

    FROM python:3.12-slim
    WORKDIR /app
  97. Question 97

    What is Kubernetes (Python)?

    Deployments, Services, probes—Helm charts common for Python services at scale.

    Example code

    # kind: Deployment
    # spec: replicas: 3
  98. Question 98

    What is Sentry (Python)?

    Error tracking with stack traces and breadcrumbs—DSN in env, scrub PII.

    Example code

    import sentry_sdk
    sentry_sdk.init(dsn="...")
  99. Question 99

    What is OpenTelemetry (Python)?

    Traces/metrics—auto-instrument ASGI/WSGI with exporters to Prometheus/Jaeger.

    Example code

    # opentelemetry-instrumentation
  100. Question 100

    What is Bandit (Python)?

    Security linter—finds common issues like hardcoded passwords, unsafe pickle.

    Example code

    # bandit -r .
  101. Question 101

    What is pip-audit (Python)?

    Reports known vulnerable dependencies—run in CI with requirements lockfile.

    Example code

    # pip-audit
  102. Question 102

    What is Hypothesis (Python)?

    Property-based testing—finds edge cases via shrinking failing examples.

    Example code

    from hypothesis import given
    import hypothesis.strategies as st
    @given(st.integers())
    def test_i(n):
        pass