Python Interview Cheatsheet
This page is a curated, question-indexed map into the rest of the cheatsheet. Each entry is a question you are likely to see in a Python interview, followed by a link that jumps directly to the section of the notes that answers it. It is intentionally a navigation layer — the actual explanations, code, and caveats live in the linked sections.
Use it two ways:
- Drilling a topic: pick a group (e.g. Asyncio) and walk every question.
- Quick review before an interview: read the questions, and for any you cannot confidently answer in one or two sentences, click through.
Python Language Fundamentals
- What does
from __future__ import ...do, and which future imports still matter? Print Function · Division · Annotations - What is
Ellipsis(...) used for in modern Python? Ellipsis - How do
for/while... elseclauses work? for ... else ... · while ... else ... - What does
try ... except ... elsedo that a plaintry ... exceptdoes not? try ... except ... else ... - How does Python handle Unicode vs bytes, and what is a code point? Characters · Unicode Code Point
Data Structures & Collections
- What is the difference between a shallow copy and a deep copy of a list? Copy Lists
- Why can
[[]] * nsurprise you? Initialize Lists with Multiplication Operator - What is a list comprehension, and when is a generator expression better? List Comprehensions
- How do you get
(index, value)pairs while iterating? enumerate() - How is a dict iterated, and what does
dict.items()/dict.keys()return? dict.keys() · dict.items() dict.setdefaultvscollections.defaultdict— which fits which use case? setdefault and defaultdict- How do you merge two dicts (pre-3.9 and post-3.9)? Merge Two Dictionaries in Python
- How would you implement an LRU cache from scratch? Implement LRU Cache with OrderedDict
- How do you dedupe a list while preserving order? Remove Duplicates from a List
- When would you use
heapqinstead of sorting? Basic Heap Operations · Priority Queue - How do you emulate a dict-like object with dunder methods? Emulate a Dictionary with Special Methods
Functions & Decorators
- What do
*argsand**kwargsreally do, and how do you forward them? Variable Arguments · Unpack Arguments - What is the difference between keyword-only and positional-only arguments? Keyword-Only Arguments · Positional-Only Arguments
- What is a closure, and what does it capture? Closure
- How do decorators work, and how do you write one that takes arguments? Decorator · Decorator with Arguments
functools.lru_cachevsfunctools.partial— what do they do? lru_cache · Partial Functions- How does
functools.singledispatchimplement function overloading? singledispatch
Iterators & Generators
- Generator function vs generator expression — when is each idiomatic? Generator Function vs Generator Expression
- How do you send a value into a running generator? Send Values to Generator
- What does
yield fromdo, and how does it compose generators? yield from Expression · yield from with Return - How do you build an iterable class with a generator method? Iterable Class via Generator
- How do you implement a context manager as a generator with
@contextmanager? Context Manager via Generator · What @contextmanager does - What is an async generator, and how does it differ from a normal generator? Async Generator
Classes & OOP
__new__vs__init__— when does each run? new vs init__str__vs__repr__— who calls which? str and repr- How does the descriptor protocol work? Descriptor Protocol
- What is the context manager protocol (
__enter__/__exit__)? Context Manager Protocol @staticmethodvs@classmethod— when to use which? staticmethod and classmethod- What is MRO, and how does C3 linearization resolve the diamond problem? The Diamond Problem (MRO)
- When should you define
__slots__? slots - How do you define a class at runtime with
type(...)? Declare Class with type() - What are abstract base classes, and how does
abcenforce them? Abstract Base Classes - How do you implement a callable object? Callable with call
- What does
@propertybuy you over plain getters/setters? @property Decorator
Concurrency
- What is the GIL, and how does it affect CPU-bound vs I/O-bound code? Understanding the GIL
- Threading vs multiprocessing — when would you reach for each? Creating Threads · Creating Processes
LockvsRLock— what is the difference? Lock · RLock- How do you synchronize with
Event,Condition, orBarrier? Event · Condition · Barrier - How would you build a producer-consumer pipeline with
queue.Queue? Producer-Consumer with Queue - What is a deadlock, and how do you prevent one? Deadlock Example and Prevention
- How do you share state across processes (Queue, Pipe, Value, Manager)? Sharing Data with Queue · Shared Memory · Manager
ThreadPoolExecutorvsProcessPoolExecutor— how do you pick? ThreadPoolExecutor · ProcessPoolExecutor- How do you process results from many futures as they complete? as_completed
Asyncio
- What actually happens when you call
asyncio.run(coro())? asyncio.run asyncio.create_taskvs awaiting a coroutine directly — what is the difference? Tasks- How do
asyncio.gatherandasyncio.waitdiffer? gather · wait for first completed - How do you time-bound an awaitable? Waiting with Timeout
- What is an async context manager, and how do you write one? Async Context Managers · @asynccontextmanager
- How do you call blocking code from an async function without blocking the loop? Running Blocking Code in Executor
- How do you handle exceptions raised inside tasks? Exception Handling in Tasks
- How do you rate-limit concurrency in asyncio? Semaphores
- What is a graceful shutdown in asyncio? Graceful Shutdown
- Conceptually, what is a coroutine and how does the event loop drive it? What is a Coroutine? · Event Loop
Common Gotchas
- Why is using a mutable default argument (
def f(x=[])) dangerous? Default Arguments
C Extensions & Interop
- How do you write a C extension module with the CPython C API? Simple C Extension · Parse Arguments
- How and why do you release the GIL in a C extension? Release the GIL
- How do you call into a shared library with
ctypes? Loading Shared Libraries · Basic Type Mapping
Networking
- How do you resolve a hostname to an IP in Python? Address Info (DNS Resolution)
- Network byte order — when and why do you need
htons/ntohs? Network Byte Order Conversion - How do you build a minimal TLS echo server and client? Simple TLS Echo Server · TLS Client
- What is mutual TLS (mTLS), and why would a service require it? Mutual TLS (mTLS)
Databases
- What does a SQLAlchemy engine actually hold, and how do connections work? Create an Engine · Database URL Format
- How do you run raw SQL safely with parameters? Connect and Execute Raw SQL
- Transactions in SQLAlchemy — who commits, and when? Transaction Management
- Core vs ORM — what does the ORM add on top? Declarative Base · Session Basics
Security & Crypto
- What are the common cryptographic mistakes to avoid? Common Mistakes · Security Checklist
- Why should you prefer
secretsoverrandomfor tokens? Secure Random Generation · Weak Random - What is a timing attack, and how do you defend against one? Timing Attacks
- How does SQL injection happen in Python, and how is it prevented? SQL Injection
See Also
If a question above is not covered, the top-level indices are the best next stop: