Pick a topic — languages & databases — 100+ questions and answers in the center column.
Python
Readable syntax, stdlib, async, data & web stacks.
102 questions
Question 1
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")Question 2
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")Question 3
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 .pycQuestion 4
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")Question 5
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"Question 6
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]Question 7
== 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]Question 8
Singleton representing absence of value; falsy. Use `x is None`, not `x == None`.
Example code
x = None
assert x is NoneQuestion 9
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]Question 10
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"] == 1Question 11
Unordered collection of unique hashable elements—fast membership and set algebra ops.
Example code
s = {1, 2, 2}
assert len(s) == 2Question 12
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]Question 13
Generator functions pause with yield, resuming on next(); memory-friendly iteration over large streams.
Example code
def gen():
yield 1
yield 2
list(gen())Question 14
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)Question 15
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()Question 16
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():
passQuestion 17
__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 = xQuestion 18
class Child(Parent): ...; super() resolves MRO (method resolution order) for cooperative multiple inheritance.
Example code
class B(A):
passQuestion 19
__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"Question 20
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]Question 21
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")Question 22
Installer for PyPI packages: pip install, requirements files, virtual environments pair with it.
Example code
# pip install requestsQuestion 23
Isolated site-packages per project—python -m venv .venv; activate to avoid polluting global Python.
Example code
# python -m venv .venvQuestion 24
Pinned or ranged dependencies for reproducible installs—pip install -r requirements.txt in CI and deploys.
Example code
# pip install -r requirements.txtQuestion 25
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)Question 26
@dataclass generates __init__, __repr__, __eq__ for simple data holders—less boilerplate than manual classes.
Example code
from dataclasses import dataclass
@dataclass
class P:
n: intQuestion 27
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 = 1Question 28
Object-oriented paths: Path('a') / 'b'—prefer over os.path for readability in 3.4+.
Example code
from pathlib import Path
Path("a") / "b"Question 29
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:
passQuestion 30
raise ValueError('msg') or raise from err to chain—bare raise re-raises current exception.
Example code
raise ValueError("msg") from NoneQuestion 31
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 timeQuestion 32
Threads share memory (GIL limits CPU parallelism). Processes have separate memory—better for CPU-heavy work on CPython.
Example code
import threading
import multiprocessingQuestion 33
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))Question 34
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())Question 35
Anonymous one-expression functions: lambda x: x+1—limited to expressions; prefer named defs for clarity.
Example code
(lambda x: x + 1)(2)Question 36
Functional builtins; list comprehensions often clearer. zip pairs iterables; itertools extends patterns.
Example code
list(zip("ab", [1, 2]))Question 37
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")Question 38
json.loads/dumps—use default= for custom types; beware float precision vs JSON numbers.
Example code
import json
json.loads("{}")Question 39
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")Question 40
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"Question 41
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}Question 42
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):Question 43
Data validation via models—used by FastAPI; v2 uses core Rust validation for speed.
Example code
from pydantic import BaseModel
class M(BaseModel):
x: intQuestion 44
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()Question 45
Database migration tool for SQLAlchemy—autogenerate from model diffs with review.
Example code
# alembic revision --autogenerateQuestion 46
Distributed task queue—brokers Redis/RabbitMQ; workers process async jobs and schedules.
Example code
from celery import Celery
app = Celery("t")Question 47
In-memory cache, pub/sub, Celery broker—redis-py or asyncio clients; watch connection pools.
Example code
import redis
r = redis.Redis()Question 48
Test framework with fixtures, parametrize, plugins—pytest -q, conftest.py for shared setup.
Example code
def test_add():
assert 1 + 1 == 2Question 49
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)Question 50
Black formats opinionated; Ruff lints extremely fast (Rust)—common pre-commit pair.
Example code
# black .
# ruff check .Question 51
Static type checker—gradual typing; strictness flags catch real bugs before runtime.
Example code
# mypy .Question 52
Project.toml dependencies, virtualenv, publish—alternative to pip+requirements for packaging.
Example code
# poetry add requestsQuestion 53
Build wheels/sdists; pyproject.toml with PEP 517 build backend—core of packaging story.
Example code
# pyproject.toml [build-system]Question 54
pip-compile locks transitive deps—reproducible requirements.in → requirements.txt.
Example code
# pip-compile requirements.inQuestion 55
Shell helpers around virtualenv—workon, mkvirtualenv for many projects.
Example code
# mkvirtualenv myprojQuestion 56
Formatted string literals: f"{x=}" for debug-style; fastest string formatting in 3.6+.
Example code
x = 3
f"{x=} {x+1=}"Question 57
:= assigns in expressions: while (line := f.readline()): ...—use sparingly for clarity.
Example code
n = (y := 5) + 1
assert n == 6 and y == 5Question 58
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)Question 59
count, cycle, chain, groupby, permutations—avoid manual index loops.
Example code
import itertools
list(itertools.pairwise([1, 2, 3]))Question 60
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)Question 61
itemgetter, attrgetter for sort keys—faster than lambdas in hot paths.
Example code
import operator
operator.add(1, 2)Question 62
defaultdict, Counter, deque, namedtuple—specialized structures over raw dict/list.
Example code
from collections import Counter
Counter("aba")Question 63
Min-heap queue—heapq.heappush/pop; nlargest/nsmallest for top-k.
Example code
import heapq
h = []
heapq.heappush(h, 3)Question 64
Binary search on sorted lists—bisect_left for insertion points.
Example code
import bisect
bisect.bisect_left([1,3,5], 4)Question 65
copy.copy shallow; copy.deepcopy for nested graphs—watch cycles and performance.
Example code
import copy
copy.deepcopy({"a": [1]})Question 66
Binary serialization of Python objects—not secure against untrusted data; prefer JSON/protobuf for APIs.
Example code
import pickle
pickle.dumps({"a": 1})Question 67
FFI to C shared libraries—struct layout and calling conventions are expert territory.
Example code
import ctypes
ctypes.c_int(42)Question 68
Compile Python-like or annotated code to C extensions—speed hot loops.
Example code
# cythonize or mypyc for compiled extensionsQuestion 69
JIT interpreter—often faster for pure Python; extension compatibility differs from CPython.
Example code
# pypy3 script.pyQuestion 70
multiprocessing, native extensions releasing GIL, or asyncio for I/O-bound concurrency.
Example code
import multiprocessing as mp
mp.PoolQuestion 71
queue.Queue thread-safe; asyncio.Queue for coroutines—coordinate producers/consumers.
Example code
import queue
queue.Queue()Question 72
futures.ThreadPoolExecutor / ProcessPoolExecutor—high-level parallel map patterns.
Example code
from concurrent.futures import ThreadPoolExecutor
ThreadPoolExecutorQuestion 73
Run external processes—capture_output, timeouts, avoid shell=True with user input.
Example code
import subprocess
subprocess.run(["echo", "hi"], capture_output=True)Question 74
Logger hierarchy, handlers, formatters—prefer over print in services; loguru optional sugar.
Example code
import logging
logging.getLogger(__name__).info("msg")Question 75
3.11+ stdlib TOML reader—for pyproject.toml; tomli on older versions.
Example code
import tomllib
# tomllib.loads(b"[a]\nb=1") # 3.11+Question 76
IANA time zones from stdlib—replace pytz for many use cases in 3.9+.
Example code
from zoneinfo import ZoneInfo
ZoneInfo("UTC")Question 77
create_task, gather, wait_for, Semaphore—backpressure and cancellation discipline.
Example code
await asyncio.gather(asyncio.sleep(0), asyncio.sleep(0))Question 78
Async HTTP client/server—ClientSession reuse; mind connector limits.
Example code
# pip install aiohttp
# ClientSession().get(url)Question 79
Sync and async HTTP—HTTP/2, similar API to requests for migration.
Example code
# pip install httpx
# httpx.get("https://example.com")Question 80
Sync HTTP for scripts—Session for connection pooling; timeouts mandatory in production.
Example code
import requests
requests.get("https://example.com", timeout=5)Question 81
HTML/XML parsing—lxml backend faster; mind encoding and malformed markup.
Example code
# pip install beautifulsoup4
# BeautifulSoup(html, "html.parser")Question 82
Fast XML/HTML; XPath—C dependencies in wheels.
Example code
# pip install lxml
# etree.fromstring(xml)Question 83
Ndarrays, vectorized math—foundation of scientific Python; avoid Python loops on large arrays.
Example code
import numpy as np
np.array([1, 2, 3]) * 2Question 84
DataFrame/Series—groupby, merge, time series; watch copy vs view semantics.
Example code
import pandas as pd
pd.Series([1, 2, 3])Question 85
Classic ML estimators—fit/predict API; pipelines for preprocessing.
Example code
from sklearn.pipeline import Pipeline
PipelineQuestion 86
Notebooks for exploration—not a deployment target; secrets and long jobs need care.
Example code
# jupyter labQuestion 87
Plotting—pyplot state machine vs OOP API; non-interactive backends in servers.
Example code
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])Question 88
Graph and eager execution—Keras high-level API; GPU via CUDA/cuDNN stacks.
Example code
import tensorflow as tf
tf.constant(1)Question 89
Dynamic graphs popular in research—torch.nn, DataLoader patterns.
Example code
import torch
torch.tensor([1.0, 2.0])Question 90
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)Question 91
QuerySet lazy until evaluated; select_related/prefetch_related kill N+1 queries.
Example code
Model.objects.select_related("fk").prefetch_related("m2m")Question 92
Serializers, viewsets, routers—permission classes and throttling for APIs.
Example code
from rest_framework import serializers
serializers.ModelSerializerQuestion 93
Pre-fork WSGI HTTP server—workers tune CPU; behind nginx for static and buffering.
Example code
# gunicorn app:appQuestion 94
ASGI server for FastAPI/Starlette—--workers for processes, not threads for async.
Example code
# uvicorn main:appQuestion 95
Reverse proxy, TLS termination, static files—pass to upstream app servers.
Example code
# proxy_pass http://127.0.0.1:8000;Question 96
Multi-stage builds slim images; non-root user; pin base image digests in production.
Example code
FROM python:3.12-slim
WORKDIR /appQuestion 97
Deployments, Services, probes—Helm charts common for Python services at scale.
Example code
# kind: Deployment
# spec: replicas: 3Question 98
Error tracking with stack traces and breadcrumbs—DSN in env, scrub PII.
Example code
import sentry_sdk
sentry_sdk.init(dsn="...")Question 99
Traces/metrics—auto-instrument ASGI/WSGI with exporters to Prometheus/Jaeger.
Example code
# opentelemetry-instrumentationQuestion 100
Security linter—finds common issues like hardcoded passwords, unsafe pickle.
Example code
# bandit -r .Question 101
Reports known vulnerable dependencies—run in CI with requirements lockfile.
Example code
# pip-auditQuestion 102
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