Names, assignment, operators, unpacking, and the small pieces of syntax used throughout Python.
printDisplay values on standard output, usually for simple program output or debugging.print('hello')
assignBind a name to an object; assignment does not copy the object.x = 1
multiple assignAssign several values to several names in one unpacking statement.a, b = 1, 2
swapExchange two values without creating a temporary variable.a, b = b, a
augmentedUpdate a value with an operator such as + or *; mutable objects may change in place.x += 1 · x *= 2
membershipCheck whether a value is contained in a sequence, set, mapping, or other container.x in seq · x not in seq
identityCheck whether two references point to the exact same object; most commonly used with None.x is None · x is not None
walrusAssign a value inside an expression so you can test it and reuse it immediately.if (n := len(items)) > 0: ...
2
Python runtime & object model
Interview · Very common
Interview-level mental model for names, objects, dynamic typing, duck typing, and what CPython actually executes.
dynamic typingTypes belong to objects rather than variable names, so the same name may later be rebound to an object of another type.value = 1 · value = 'one'
names bind objectsAssignment binds a name to an existing object; it does not copy that object unless you explicitly create a copy.b = a
duck typingCode usually depends on the operations an object supports rather than requiring one exact declared class.stream.read() works for any compatible object
source → bytecodeCPython compiles Python source to bytecode before executing it with the interpreter rather than executing source text directly line by line.import dis · dis.dis(function)
typetype() returns an object's runtime type and is useful for inspection, though polymorphic code often prefers capability checks or isinstance().type(value)
isinstanceCheck whether an object is an instance of a class or any subclass, which is usually safer than exact type equality.isinstance(value, str)
None singletonNone is a singleton sentinel for absence, so identity comparison is the conventional and reliable check.value is None
arguments bind referencesFunction parameters become local names bound to the caller's objects, so mutating a passed mutable object can be visible to the caller.def add(items): items.append('x')
3
Collections
Interview · Very common
Store groups of values using lists, tuples, sets, and dictionaries, each with different behavior.
listOrdered, mutable sequence whose items can be added, removed, replaced, or reordered.items = [1, 2, 3]
append / extendappend adds one item; extend adds every item from another iterable.items.append(x) · items.extend(xs)
insert / popInsert an item at a position, or remove and return an item from a position.items.insert(i, x) · items.pop(i)
sortlist.sort() mutates a list; sorted() returns a new sorted list from any iterable.items.sort(key=fn) · sorted(items, reverse=True)
tupleOrdered, immutable sequence; a one-item tuple needs a trailing comma.point = (10, 20) · single = (1,)
setMutable collection of unique hashable values, useful for membership tests and deduplication.unique = {1, 2, 3} · set(items)
set opsCompute union, intersection, difference, or symmetric difference between sets.a | b · a & b · a - b · a ^ b
dictMutable mapping from unique hashable keys to values.user = {'name': 'Ada'}
dict getRead a mapping value without raising KeyError when the key is absent.user.get('name', 'Unknown')
dict iterateIterate through dictionary keys and values together.for k, v in user.items(): ...
4
Mutability & References
Interview · Very common
The key mental model: variables are names bound to objects. Mutation changes an object; assignment changes what a name points to.
mutableThe object can change in place, so every reference to that same object observes the change.list · dict · set · most class instances
immutableThe object itself cannot change in place; an apparent update creates another value and rebinds a name.int · float · bool · str · tuple · frozenset · bytes
assignment bindsAssignment points a name at an object. It does not clone the object.b = a
aliasingTwo names can refer to the same mutable object, so mutation through one name is visible through the other.b = a · b.append(1) · a also changed
rebind vs mutateRebinding changes which object a name refers to; mutation changes the existing object itself.x = x + [1] vs x.append(1)
function argumentsParameters are new local names bound to the caller's objects; mutating a passed mutable object can affect caller-visible state.def add(items): items.append('x')
shallow copyCreate a new outer container while keeping references to the same nested objects.b = a.copy() · copy.copy(a)
deep copyRecursively copy nested state when the new structure really must be independent.b = copy.deepcopy(a)
5
Identity, Hashing & Truthiness
Interview · Very common
Three related rules decide how values compare, whether they can be keys, and how they behave inside conditions.
== equalityCompare values using equality semantics, which classes can customize with __eq__.a == b
is identityCheck whether both references point to the exact same object. Prefer it for None and unique sentinels.value is None
hashableA value has stable hash/equality behavior and may be used as a dictionary key or set member.str · int · frozenset · tuple of hashable values
unhashableCommon mutable containers are deliberately unhashable because changing them would break hash-based lookup.list · dict · set
truthy / falsyConditions ask for a value's truth value; values are not required to literally be True or False.if items: ...
common falsyNone, false booleans, numeric zero, and empty containers/text evaluate as false.None · False · 0 · 0.0 · '' · [] · {} · set()
and / orBoolean operators short-circuit and return one of their operands, which makes fallback expressions possible.name = raw_name or 'Unknown'
notConvert a value to its truth value and negate it, producing a real bool.if not items: ...
6
Internals & Gotchas
Interview · Very common
Common Python behaviors that cause subtle bugs when object identity, mutation, copying, or evaluation is misunderstood.
mutable defaultA mutable default is created once when the function is defined, so calls can accidentally share state.avoid def f(items=[]); use None + create inside
late bindingClosures normally read captured names when called, not when the closure was created.lambda x=x: x captures the current loop value
identity vs equalityis asks whether two references are the same object; == asks whether their values compare equal.is → same object · == → equal value
shallow copyCopy only the outer object; nested objects are still shared.copy.copy(obj) · list.copy()
deep copyRecursively copy nested state, which is more independent but can be expensive or inappropriate.copy.deepcopy(obj)
truthinessConditions accept any value; Python converts it using truth-value rules instead of requiring a literal bool.False: None, False, 0, '', [], {}, set()
hashabilityDictionary keys and set members need stable hash/equality behavior.dict/set keys must be hashable
iterator exhaustionMost iterators are one-pass; once consumed, they do not restart automatically.iterators are consumed; recreate or materialize if needed
7
Strings
Interview · Very common
Create, inspect, split, combine, search, format, encode, and transform text.
index / sliceRead one character or part of a string; negative indexes count from the end and [::-1] reverses it.s[0] · s[-1] · s[1:5] · s[::-1]
stripRemove whitespace from both ends; lstrip and rstrip remove it from only one side.s.strip() · s.lstrip() · s.rstrip()
splitBreak text into a list using a separator, or split it by line boundaries.s.split(',') · s.splitlines()
joinCombine strings using the string before .join() as the separator.', '.join(parts)
replaceReturn a new string with matching text replaced; strings themselves are immutable.s.replace('old', 'new')
findFind the first match position; find returns -1 when missing, while index raises ValueError.s.find('x') · s.index('x')
prefix / suffixCheck whether text starts or ends with a specific string.s.startswith('Py') · s.endswith('.py')
f-stringInsert values or expressions directly into text; :.2f formats a number to two decimal places.f'{name}: {value:.2f}'
8
Functions
Interview · Very common
Define reusable behavior, control how arguments are accepted, and understand how names are resolved.
defineCreate a reusable callable with named parameters and a return value.def add(a, b): return a + b
default argUse a fallback argument when the caller omits it; avoid mutable objects as defaults.def greet(name='World'): ...
*argsCollect extra positional arguments into a tuple.def f(*args): ...
**kwargsCollect extra keyword arguments into a dictionary.def f(**kwargs): ...
keyword-onlyRequire arguments after * to be passed by name.def f(a, *, timeout=5): ...
positional-onlyRequire arguments before / to be passed by position.def f(a, /, b): ...
unpack callExpand an iterable into positional arguments and a mapping into keyword arguments.f(*args, **kwargs)
lambdaCreate a small anonymous single-expression function, often used as a key or callback.key=lambda item: item.name
9
Control Flow
Interview · Very common
Choose what runs, repeat work, and control whether a loop stops, skips, or continues.
if / elif / elseRun the first branch whose condition is true, otherwise run the optional else branch.if x > 0: ...
ternaryChoose between two values inside a single expression.label = 'yes' if ok else 'no'
forTake items from an iterable one at a time and run the loop body for each item.for item in items: ...
whileRepeat a block while its condition remains true.while condition: ...
breakExit the nearest loop immediately.break
continueSkip the rest of the current loop iteration and continue with the next one.continue
enumerateLoop over values while also receiving their index counter.for i, x in enumerate(items): ...
zipLoop over multiple iterables in parallel, pairing corresponding items.for a, b in zip(xs, ys): ...
10
Comprehensions
Interview · Very common
Build collections or lazy generators compactly from other iterables, optionally filtering values.
list compBuild a new list by transforming each item from an iterable.[x * x for x in items]
filterBuild a list containing only items that satisfy a condition.[x for x in items if x > 0]
transform + filterFilter input items and transform the ones that remain in one expression.[f(x) for x in items if ok(x)]
set compBuild a set from transformed items, automatically keeping only unique values.{normalize(x) for x in items}
dict compBuild a dictionary by computing each key and value.{x: f(x) for x in items}
generator exprCreate values lazily instead of building the entire collection in memory.(f(x) for x in items)
conditional valueChoose between two output values for every item inside a comprehension.['even' if x % 2 == 0 else 'odd' for x in nums]
11
OOP
Interview · Very common
Model state and behavior with classes, instances, inheritance, properties, and alternative constructors.
classDefine a type that groups state and behavior for its instances.class User: ...
constructorInitialize a newly created instance; self is the instance being initialized.def __init__(self, name): self.name = name
instance methodDefine behavior that receives the instance as its first argument.def save(self): ...
inheritanceCreate a subclass that reuses and can override behavior from a base class.class Admin(User): ...
superCall the next implementation in the method-resolution order, usually a base-class method.super().__init__(name)
propertyExpose method-backed behavior through normal attribute syntax.@property · @value.setter
class methodDefine a method that receives the class as cls, often for alternate constructors.@classmethod · def from_json(cls, raw): ...
static methodNamespace a function inside a class without automatically receiving self or cls.@staticmethod · def validate(value): ...
12
Exceptions
Interview · Very common
Represent failures explicitly, catch only expected errors, and guarantee cleanup when execution leaves a block.
try / exceptRun code that may fail and handle a specific expected exception.try: ... · except ValueError as exc: ...
multiple typesHandle several exception types with the same recovery logic.except (TypeError, ValueError): ...
elseRun code only when the try block completed without an exception.else: ... # only if no exception
finallyRun cleanup code whether the try block succeeds, fails, returns, or exits a loop.finally: ... # always runs
raiseCreate or propagate an exception deliberately when an operation cannot continue correctly.raise ValueError('invalid value')
re-raisePropagate the currently handled exception unchanged after logging or partial handling.except Exception: log(); raise
causeWrap a lower-level exception while preserving it as the explicit cause.raise DomainError() from exc
custom errorCreate an exception type that expresses a failure meaningful to your application.class DomainError(Exception): pass
13
Context managers
Interview · Very common
Use with to pair resource acquisition and guaranteed cleanup, including custom and generator-based context managers.
withEnter a managed resource for a block and guarantee its exit logic runs when the block finishes, including when an exception occurs.with open(path) as f: data = f.read()
__enter__Called when entering a with block; its return value becomes the object bound after as.def __enter__(self): return self.resource
__exit__Called when leaving a with block with exception information when relevant, making it the cleanup hook for class-based managers.def __exit__(self, exc_type, exc, tb): self.close()
suppress from __exit__Returning a truthy value from __exit__ tells Python that a raised exception was handled and should not propagate.return isinstance(exc, ExpectedError)
@contextmanagerCreate a context manager from one generator function instead of writing a class with __enter__ and __exit__ methods.@contextmanager · def resource(): ...
yield boundaryIn a @contextmanager function, code before yield is setup and code after yield is teardown that resumes when the with block exits.acquire(); try: yield obj; finally: release()
multiple contextsManage several resources in one with statement; cleanup occurs in reverse order of successful entry.with open(a) as fa, open(b) as fb: ...
lock contextSynchronization primitives such as threading.Lock are context managers, so with lock gives exception-safe acquire/release behavior.with lock: shared.append(item)
14
Iterators & Generators
Interview · Very common
Understand Python's iteration protocol and produce values lazily instead of building everything at once.
iteratorStateful object that produces one value at a time until it is exhausted.it = iter(items)
nextRequest the next iterator value; without a default, exhaustion raises StopIteration.next(it) · next(it, default)
generatorFunction containing yield; calling it creates a lazy iterator that preserves state between values.def gen(): yield value
yield fromDelegate yielding to another iterable or generator.yield from iterable
generator exprCreate a lazy iterator with comprehension-like syntax.(x * x for x in items)
chainTreat several iterables as one continuous sequence without copying their contents.itertools.chain(a, b)
isliceTake a slice-like window from an iterator without first converting it to a list.itertools.islice(stream, 10)
count / cycleCreate an unbounded counter or endlessly repeat an iterable; the consumer must decide when to stop.itertools.count() · itertools.cycle(seq)
15
Decorators
Interview · Very common
Understand what @decorator syntax actually does, how wrappers and closures work, and how to preserve the wrapped function correctly.
decoratorA decorator receives a function or class and returns the object that should replace it after definition.@trace · def run(): ...
syntax equivalenceDecorator syntax is assignment performed after the function is created; @trace means run = trace(run).run = trace(run)
wrapperA typical function decorator returns an inner wrapper that adds behavior before or after calling the original function.def wrapper(*args, **kwargs): return func(*args, **kwargs)
functools.wrapsCopy important metadata and expose __wrapped__ so the decorated function still behaves well with docs, debugging, and introspection tools.@wraps(func)
forward argumentsGeneric wrappers normally accept and forward *args and **kwargs so they do not accidentally restrict the wrapped callable's signature.return func(*args, **kwargs)
decorator factoryA decorator that itself accepts configuration uses one extra function level: configuration → decorator → wrapper.@retry(attempts=3)
stacked decoratorsStacked decorators apply from the function outward, so @a above @b produces a(b(function)).@a · @b · def f(): ... → f = a(b(f))
closureThe returned wrapper can keep access to variables from the enclosing decorator scope even after that outer function has returned.def trace(func): def wrapper(): return func()
16
Testing
Interview · Very common
Express expected behavior, isolate dependencies, prepare reusable test data, and run focused automated checks.
assertFail the current test when the expected condition is false.assert actual == expected
unittest caseCreate a unittest test class whose methods define individual test cases.class TestThing(unittest.TestCase): ...
unittest equalityAssert that two values compare equal using unittest's diagnostic output.self.assertEqual(actual, expected)
mockCreate a controllable test double that records calls and can return configured values.Mock(return_value=value)
patchTemporarily replace the name used by code under test and restore it automatically afterward.with patch('module.client') as mock_client: ...
pytest testDefine a pytest test as a normal function whose failures are reported from assertions/exceptions.def test_feature(): ...
pytest fixtureProvide reusable setup or test data through pytest dependency injection by parameter name.@pytest.fixture · def client(): ...
pytest raisesAssert that a block raises the expected exception type.with pytest.raises(ValueError): ...
17
pytest fixtures & parametrization
Interview · Very common
The pytest mechanics most often discussed in automation interviews: dependency injection, yield teardown, scope, parametrization, and built-in fixtures.
fixture injectionA test requests a fixture by naming it as a function argument; pytest resolves and executes the matching fixture before calling the test.def test_user(client): ...
fixture returnA normal fixture runs its setup code once for that fixture instance and returns the object that pytest passes into dependent tests or fixtures.@pytest.fixture · def client(): return Client()
yield fixtureCode before yield is setup, the yielded value is injected into the test, and pytest resumes the fixture after the test finishes to run teardown.connect(); yield device; disconnect()
fixture scopeScope controls how long one fixture instance is reused: function, class, module, package, or session.@pytest.fixture(scope='session')
fixture dependencyFixtures can depend on other fixtures through their own parameters, letting pytest build the dependency graph in the required order.def authenticated_client(client, token): ...
autouseAn autouse fixture applies automatically within its scope even when tests do not name it explicitly; use it sparingly because dependencies become less visible.@pytest.fixture(autouse=True)
parametrizeRun one test function against multiple explicit data sets while pytest reports each case as a separate test invocation.@pytest.mark.parametrize(('x', 'expected'), [(1, 2), (2, 4)])
pytest.raisesAssert that a specific operation raises an expected exception and optionally inspect the captured exception object.with pytest.raises(ValueError): parse('bad')
18
HTTP clients for automation
Interview · Very common
Practical HTTP patterns for API tests and helpers: parameters, JSON, sessions, status handling, timeouts, and sync/async clients.
requests GETMake a synchronous HTTP request with the requests library and always provide an explicit timeout in automation code.response = requests.get(url, timeout=5)
query paramsPass query parameters as structured data instead of manually concatenating and escaping them into the URL.requests.get(url, params={'page': 2}, timeout=5)
JSON bodyUse the json argument to serialize a Python object as JSON and set the appropriate content type automatically.requests.post(url, json={'name': 'Ada'}, timeout=5)
headersPass request headers explicitly for authentication, content negotiation, correlation IDs, or other protocol metadata.headers={'Authorization': f'Bearer {token}'}
raise_for_statusConvert unsuccessful HTTP status responses into exceptions when a helper expects a successful request instead of silently continuing.response.raise_for_status()
response JSONDecode a JSON response into Python values; still validate status, schema, and expected fields rather than assuming the body is correct.payload = response.json()
SessionReuse cookies, headers, and pooled connections across related requests instead of creating fully independent top-level calls each time.with requests.Session() as session: session.get(url, timeout=5)
httpx.Clienthttpx provides a requests-like synchronous client with modern timeout and connection-pooling APIs and a matching asynchronous client.with httpx.Client(timeout=5) as client: client.get(url)
19
Timeout, polling & retry
Interview · Very common
Bound waiting explicitly: use deadlines, poll observable conditions, and retry only failures that can reasonably succeed later.
timeoutEvery operation that can block on an external dependency should have a finite timeout so a failure cannot hang the entire test or worker indefinitely.requests.get(url, timeout=5)
monotonic deadlineUse time.monotonic for elapsed-time deadlines because wall-clock changes do not move it backward or forward unexpectedly.deadline = time.monotonic() + 10
poll conditionRepeatedly check the actual condition you need until it becomes true or the overall deadline expires instead of sleeping once and hoping.while time.monotonic() < deadline: status = get_status()
bounded retryLimit retries by attempt count or deadline so a persistent failure is surfaced rather than converted into an infinite loop.for attempt in range(3): ...
transient onlyRetry failures that may genuinely recover, such as temporary network errors or selected server responses, not deterministic validation or assertion failures.retry TimeoutError, not ValueError from bad test data
exponential backoffIncrease the delay between attempts to reduce pressure on a dependency that may already be overloaded or recovering.delay = min(base * 2 ** attempt, cap)
jitterAdd randomness to retry delays so many workers do not all retry at the same instant and create another traffic spike.sleep(random.uniform(0, delay))
last failureWhen retries are exhausted, preserve the final exception and useful attempt diagnostics instead of raising an unrelated generic timeout with no cause.raise RetryError(...) from last_exc
20
GIL, threads, processes & asyncio
Interview · Very common
Choose the concurrency model from the workload: I/O waiting, CPU work, shared memory, process isolation, or cooperative async I/O.
concurrency vs parallelismConcurrency means tasks can make progress during overlapping time; parallelism means multiple tasks are literally executing at the same time.asyncio = concurrency · processes = parallel CPU work
GILIn the default CPython build, the Global Interpreter Lock allows only one thread at a time to execute Python bytecode.CPU-bound Python threads do not normally scale across cores
threadingThreads share one process and memory space, making them lightweight and useful when work spends most of its time waiting on blocking I/O.ThreadPoolExecutor for network/file I/O
multiprocessingProcesses have separate interpreters and memory, so CPU-bound Python can run on multiple cores at the cost of higher startup and communication overhead.ProcessPoolExecutor for CPU-heavy work
asyncioOne event loop cooperatively switches between coroutines at await points, making it efficient for many concurrent I/O operations without one thread per task.await network_call() yields control to the loop
I/O-boundWhen most time is spent waiting for network, files, databases, or external services, threads or asyncio can overlap that waiting effectively.HTTP scraper → asyncio or threads
CPU-boundWhen most time is spent executing Python computations, processes are the usual default-build choice for true multi-core parallelism.image/data computation → processes
race conditionShared mutable state can still be corrupted when operations interleave, so protect critical sections with synchronization rather than relying on the GIL.with lock: counter += 1
21
Typing
Interview · Common
Describe expected value shapes for editors, static type checkers, documentation, and safer refactoring.
annotationAttach an expected type to a name for readers, editors, and static type checkers.name: str = 'Ada'
unionAllow a value to have any one of several declared types.value: int | str
optionalAllow either the declared value type or None.value: str | None
collectionsDescribe element types inside generic collections such as lists and dictionaries.items: list[str] · mapping: dict[str, int]
tupleDescribe the type of each position in a tuple.point: tuple[int, int]
CallableDescribe the parameter types and return type of a callable.Callable[[str], int]
LiteralRestrict a value to specific literal choices during static checking.Literal['GET', 'POST']
type aliasGive a reusable name to a type expression so annotations stay readable.type UserId = int
22
Modules / Imports
Interview · Common
Split code into modules and packages, import public names, and control module execution.
importLoad a module and bind its module object to a name.import math
aliasBind an imported module to a shorter or clearer local name.import pathlib as pl
from importImport selected names directly into the current namespace.from pathlib import Path
import aliasImport one selected object under a different local name.from module import long_name as short
relative importImport from the current package using dots to express relative package location.from .helpers import parse
main guardRun code only when the file is executed as the entry module, not when it is imported.if __name__ == '__main__': main()
public APIDeclare the names intended for wildcard export and document the module's public surface.__all__ = ['Client', 'connect']
run moduleExecute a module through Python's module loader while preserving package import behavior.python -m package.module
23
Virtual environments & packaging
Interview · Common
The project-isolation and dependency-management commands expected in practical Python interviews and day-to-day automation work.
create venvCreate a project-specific virtual environment with its own interpreter context and isolated site-packages directory.python -m venv .venv
activationActivation mainly adjusts the shell PATH so python and installed console scripts resolve to the environment; using the environment's interpreter directly also works.Windows: .venv\Scripts\Activate.ps1 · POSIX: source .venv/bin/activate
python -m pipRun pip through the intended Python interpreter so package installation goes to the environment you actually selected.python -m pip install pytest
requirementsInstall a declared set of dependencies from a requirements file rather than manually recreating the environment package by package.python -m pip install -r requirements.txt
pyproject.tomlModern Python projects use pyproject.toml for build-system configuration, project metadata, dependencies, and tool-specific configuration.[build-system] · [project] · [tool.pytest.ini_options]
project dependenciesDeclare runtime package requirements as project metadata when the project is packaged rather than hiding them only in developer setup notes.[project] dependencies = ['requests>=2.32']
dependency groupsUse standardized pyproject dependency groups for development-only sets such as test or docs dependencies when your tooling supports them.[dependency-groups] test = ['pytest', 'coverage']
editable installInstall the current project so imports resolve through the working source tree while development changes remain immediately visible.python -m pip install -e .
24
Files & Pathlib
Interview · Common
Read, write, locate, create, rename, and inspect files and directories safely.
read textRead an entire text file into a string using the requested character encoding.Path('file.txt').read_text(encoding='utf-8')
write textWrite a complete string to a text file and return the number of characters written.Path('file.txt').write_text(text, encoding='utf-8')
open safelyOpen a file inside a context manager so it is closed even if an error occurs.with open(path, encoding='utf-8') as f: ...
binary modeRead raw bytes instead of decoded text.with open(path, 'rb') as f: data = f.read()
join pathCombine path components using Path semantics instead of manual separators.path = Path('data') / 'items.json'
exists / typeCheck whether a path exists and whether it represents a file or directory.path.exists() · path.is_file() · path.is_dir()
JSON fileRead JSON directly from a file object or write Python data directly to one.json.load(f) · json.dump(obj, f)
CSV rowsRead or write CSV data as sequences of column values.csv.reader(f) · csv.writer(f)
CSV dictsRead or write CSV rows using column names as dictionary keys.csv.DictReader(f) · csv.DictWriter(f, fields)
TOMLParse TOML configuration data with Python's built-in tomllib reader.tomllib.load(f)
INICreate a parser for INI-style section/key configuration files.configparser.ConfigParser()
pickleSerialize and restore Python-specific objects; use only with trusted data.pickle.load(f) · pickle.dump(obj, f)
26
Regular expressions
Interview · Common
The re operations most useful in interviews and automation: search, full validation, extraction, replacement, compiled patterns, groups, and flags.
raw patternWrite regular-expression patterns as raw strings in most cases so Python string escaping does not compete with regex backslashes.pattern = r'\d+'
re.searchFind the first match anywhere in the string and return a match object or None when no match exists.match = re.search(r'ID=(\d+)', text)
re.matchAttempt a match only at the beginning of the string; it does not require the pattern to consume the entire string.re.match(r'GET', request_line)
re.fullmatchRequire the entire string to satisfy the pattern, which is usually clearer than manually anchoring validation patterns.re.fullmatch(r'[A-Z]{3}-\d{4}', code)
re.findallReturn all non-overlapping matches as strings or tuples, useful when you need the complete set of extracted values at once.ids = re.findall(r'ID=(\d+)', text)
re.finditerIterate lazily over match objects when you need positions, groups, or many matches without building one result list first.for match in re.finditer(pattern, text): ...
re.subReturn text with matching regions replaced by a string or replacement function.masked = re.sub(r'\d', '*', card_number)
re.compileCreate a reusable pattern object when the same expression is applied repeatedly or when storing a configured pattern improves readability.token_re = re.compile(r'Bearer\s+(.+)')
27
Dataclasses / Enum
Interview · Common
Reduce class boilerplate for data objects and represent a fixed set of named values.
dataclassGenerate common data-object methods such as __init__ and __repr__ from annotated fields.@dataclass · class Point: x: int; y: int
default factoryCreate a fresh default object for each dataclass instance, avoiding shared mutable defaults.field(default_factory=list)
frozenPrevent normal field reassignment after a dataclass instance is created.@dataclass(frozen=True)
slotsGenerate a slotted dataclass with a fixed attribute layout and usually lower memory overhead.@dataclass(slots=True)
asdictConvert a dataclass instance recursively into standard dictionaries and collections.asdict(instance)
replaceCreate a new dataclass instance with selected fields changed.replace(instance, x=10)
EnumDefine a fixed set of named values with identity and readable names.class Color(Enum): RED = 1
autoLet Enum generate member values automatically.RED = auto()
28
Dunder Methods
Interview · Common
Hook your objects into Python syntax such as printing, comparison, iteration, indexing, and context managers.
representationControl developer-oriented repr() output and user-oriented str() output.__repr__ · __str__
lengthDefine what len(obj) returns.__len__
iterationMake an object iterable and, for iterators, define how the next item is produced.__iter__ · __next__
membershipCustomize the behavior of value in obj.__contains__
indexingCustomize reading or assigning values with square-bracket syntax.__getitem__ · __setitem__
callable objectAllow an instance to be called like a function.__call__
comparisonCustomize equality and ordering operators for your objects.__eq__ · __lt__ · __le__
hashingDefine a stable hash so compatible immutable objects can be dictionary keys or set members.__hash__
29
Concurrency
Interview · Common
Choose between synchronous code, async I/O, threads, and processes based on what is waiting or consuming CPU.
async functionDefine a coroutine function; calling it creates a coroutine that must be awaited or scheduled.async def fetch(): ...
awaitPause the current coroutine until another awaitable completes while allowing the event loop to run other work.result = await fetch()
run event loopStart an event loop, run the top-level coroutine, and cleanly shut the loop down.asyncio.run(main())
create taskSchedule a coroutine to run concurrently on the current event loop.task = asyncio.create_task(coro())
gatherWait for several awaitables and return their results in input order.results = await asyncio.gather(*coros)
TaskGroupRun related async tasks as one structured unit and propagate failures together.async with asyncio.TaskGroup() as tg: ...
thread poolUse operating-system threads, typically for blocking I/O or code that releases the GIL.with ThreadPoolExecutor() as ex: ex.map(fn, items)
process poolUse separate processes for CPU-heavy Python work that benefits from true parallel execution.with ProcessPoolExecutor() as ex: ex.map(fn, items)
30
Memory management & profiling
Interview · Common
Know the CPython memory model at interview depth, then measure CPU and memory behavior before attempting optimization.
reference countingThe default CPython build primarily tracks how many references point to ordinary objects and can usually reclaim them when that count reaches zero.dropping the last reference usually releases an ordinary object promptly
cyclic GCA separate garbage collector supplements reference counting by finding unreachable reference cycles whose members would otherwise keep one another alive.two objects referencing each other can still be collected
deldel removes a name, item, or attribute reference; it does not guarantee the underlying object is destroyed if other references still exist.del obj
gc.collectTrigger an explicit garbage-collection pass for diagnostic or unusual lifecycle needs; normal application code should rarely need to force collection.collected = gc.collect()
sys.getsizeofReport the shallow size of one object itself; referenced child objects are not recursively included in that number.sys.getsizeof(items)
tracemallocTrace Python memory allocations and compare snapshots to locate where memory growth is being allocated.tracemalloc.start() · snapshot = tracemalloc.take_snapshot()
cProfileProfile function calls and cumulative CPU time to locate actual hot paths before rewriting code based on intuition.python -m cProfile -s cumulative script.py
timeitMeasure a small code path repeatedly under a controlled harness when comparing micro-level implementation choices.python -m timeit 'sum(range(100))'
31
Logging / Debugging
Interview · Common
Observe what a program is doing, inspect failures, stop execution interactively, and measure small code paths.
basic configConfigure a simple root logging setup, typically once near program startup.logging.basicConfig(level=logging.INFO)
loggerCreate or retrieve a named logger, usually using the module name.log = logging.getLogger(__name__)
levelsWrite messages with severity levels from detailed debugging through errors.log.debug() · info() · warning() · error()
exceptionLog a message together with the current exception traceback from inside an except block.log.exception('operation failed')
breakpointPause execution and enter the configured interactive debugger.breakpoint()
pdbRun a script under Python's built-in command-line debugger.python -m pdb script.py
tracebackPrint the traceback for the exception currently being handled.traceback.print_exc()
timeitMeasure execution time repeatedly for a small code snippet or callable.timeit.timeit('fn()', globals=globals(), number=1000)
32
OS / CLI
Interview · Common
Interact with the operating system, environment variables, command-line arguments, subprocesses, and temporary files.
cwdRead or change the process's current working directory.os.getcwd() · os.chdir(path)
environmentRead environment variables or access the environment mapping directly.os.getenv('KEY') · os.environ['KEY']
CLI argsRead the raw command-line arguments passed to the Python process.sys.argv
exitStop the program intentionally with a process exit status.sys.exit(1)
run commandRun an external command and optionally fail immediately when its exit code is non-zero.subprocess.run(cmd, check=True)
capture outputRun a command while capturing stdout/stderr as text instead of printing it.subprocess.run(cmd, capture_output=True, text=True)
copy / moveCopy file metadata-preserving content or move files/directories to another path.shutil.copy2(src, dst) · shutil.move(src, dst)
temporary dirCreate a temporary directory that is automatically removed when the context exits.with tempfile.TemporaryDirectory() as tmp: ...
33
Numbers
Interview · Common
Work with integers, floating-point values, precise decimals, fractions, and common math operations.
numeric typesUse int for whole numbers, float for binary floating point, and complex for real-plus-imaginary values.int · float · complex
division/ returns true division, // floors the quotient, and % returns the remainder.7 / 3 · 7 // 3 · 7 % 3
powerRaise a value to a power with ** or pow().2 ** 8 · pow(2, 8)
abs / roundGet a magnitude with abs(), or round a number to a requested precision.abs(x) · round(x, 2)
divmodCompute quotient and remainder together in one operation.q, r = divmod(a, b)
basesConvert integers to binary/octal/hex text, or parse text using a specific numeric base.bin(n) · oct(n) · hex(n) · int('ff', 16)
mathUse common mathematical functions such as square root, ceiling, and floor.math.sqrt(x) · math.ceil(x) · math.floor(x)
iscloseCompare floating-point values using a tolerance instead of exact equality.math.isclose(a, b, rel_tol=1e-9)
34
Datetime
Interview · Occasional
Represent dates, times, durations, timestamps, and time zones without losing temporal context.
todayReturn the current local calendar date without a time component.date.today()
UTC nowReturn the current time as a timezone-aware UTC datetime.datetime.now(timezone.utc)
durationRepresent a span of time that can be added to or subtracted from dates and datetimes.timedelta(days=1, hours=2)
parseConvert text matching an explicit format pattern into a datetime.datetime.strptime(text, '%Y-%m-%d')
formatConvert a datetime into formatted text using strftime directives.dt.strftime('%Y-%m-%d %H:%M')
ISO parseParse an ISO-8601-style date/time string into a datetime.datetime.fromisoformat(text)
ISO formatSerialize a date or datetime to an ISO-8601-style string.dt.isoformat()
timezoneLoad an IANA time zone with real daylight-saving and historical offset rules.ZoneInfo('Europe/Kyiv')
35
Stdlib Toolbox
Interview · Occasional
Useful batteries-included data structures and algorithms that often replace custom utility code.
CounterCount occurrences of hashable items and retrieve the most common values.Counter(items).most_common(3)
defaultdictCreate a dictionary that automatically supplies a default value for missing keys.defaultdict(list)
dequeUse a double-ended queue with efficient appends and pops from both ends.deque(items, maxlen=100)
cacheMemoize all calls by arguments with an unbounded function cache.@functools.cache
LRU cacheMemoize recent calls while limiting how many argument/result pairs are retained.@functools.lru_cache(maxsize=128)
partialCreate a new callable with some arguments pre-filled.functools.partial(fn, fixed_arg)
heapMaintain a min-heap so the smallest item can be pushed and popped efficiently.heapq.heappush(heap, x) · heapq.heappop(heap)
bisectInsert or search in a sorted list while preserving its sort order.bisect.insort(sorted_items, x)
36
SQLite
Interview · Occasional
Use Python's built-in SQLite driver for lightweight relational storage, queries, parameters, and transactions.
connectOpen a SQLite database file and return a connection object.con = sqlite3.connect('app.db')
executeExecute one SQL statement through a connection or cursor.con.execute('SELECT * FROM users')
parametersBind values separately from SQL text to avoid quoting bugs and SQL injection.con.execute('SELECT * FROM users WHERE id = ?', (user_id,))
fetch oneReturn the next result row, or None when no rows remain.row = cursor.fetchone()
fetch allLoad all remaining result rows into a list.rows = cursor.fetchall()
transactionUse the connection as a context manager so successful work commits and exceptions roll back.with con: con.execute(...)
row mappingReturn rows that support both index access and column-name access.con.row_factory = sqlite3.Row
insert manyExecute one parameterized statement repeatedly for many rows of values.con.executemany(sql, rows)