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? → basic/python-future: Print Function · Division · AnnotationsWhat is
Ellipsis(...) used for in modern Python? → basic/python-basic: EllipsisHow do
for/while... elseclauses work? → basic/python-basic: for … else … · while … else …What does
try ... except ... elsedo that a plaintry ... exceptdoes not? → basic/python-basic: try … except … else …How does Python handle Unicode vs bytes, and what is a code point? → basic/python-unicode: Characters · Unicode Code Point
Data Structures & Collections#
What is the difference between a shallow copy and a deep copy of a list? → basic/python-list: Copy Lists
Why can
[[]] * nsurprise you? → basic/python-list: Initialize Lists with Multiplication OperatorWhat is a list comprehension, and when is a generator expression better? → basic/python-list: List Comprehensions
How do you get
(index, value)pairs while iterating? → basic/python-list: enumerate()How is a dict iterated, and what does
dict.items()/dict.keys()return? → basic/python-dict: dict.keys() · dict.items()dict.setdefaultvscollections.defaultdict— which fits which use case? → basic/python-dict: setdefault and defaultdictHow do you merge two dicts (pre-3.9 and post-3.9)? → basic/python-dict: Merge Two Dictionaries in Python
How would you implement an LRU cache from scratch? → basic/python-dict: Implement LRU Cache with OrderedDict
How do you dedupe a list while preserving order? → basic/python-set: Remove Duplicates from a List
When would you use
heapqinstead of sorting? → basic/python-heap: Basic Heap Operations · Priority QueueHow do you emulate a dict-like object with dunder methods? → basic/python-dict: Emulate a Dictionary with Special Methods
Functions & Decorators#
What do
*argsand**kwargsreally do, and how do you forward them? → basic/python-func: Variable Arguments · Unpack ArgumentsWhat is the difference between keyword-only and positional-only arguments? → basic/python-func: Keyword-Only Arguments · Positional-Only Arguments
What is a closure, and what does it capture? → basic/python-func: Closure
How do decorators work, and how do you write one that takes arguments? → basic/python-func: Decorator · Decorator with Arguments
functools.lru_cachevsfunctools.partial— what do they do? → basic/python-func: lru_cache · Partial FunctionsHow does
functools.singledispatchimplement function overloading? → basic/python-func: singledispatch
Iterators & Generators#
Generator function vs generator expression — when is each idiomatic? → basic/python-generator: Generator Function vs Generator Expression
How do you send a value into a running generator? → basic/python-generator: Send Values to Generator
What does
yield fromdo, and how does it compose generators? → basic/python-generator: yield from Expression · yield from with ReturnHow do you build an iterable class with a generator method? → basic/python-generator: Iterable Class via Generator
How do you implement a context manager as a generator with
@contextmanager? → basic/python-generator: Context Manager via Generator · What @contextmanager doesWhat is an async generator, and how does it differ from a normal generator? → basic/python-generator: Async Generator
Classes & OOP#
__new__vs__init__— when does each run? → basic/python-object: __new__ vs __init____str__vs__repr__— who calls which? → basic/python-object: __str__ and __repr__How does the descriptor protocol work? → basic/python-object: Descriptor Protocol
What is the context manager protocol (
__enter__/__exit__)? → basic/python-object: Context Manager Protocol@staticmethodvs@classmethod— when to use which? → basic/python-object: staticmethod and classmethodWhat is MRO, and how does C3 linearization resolve the diamond problem? → basic/python-object: The Diamond Problem (MRO)
When should you define
__slots__? → basic/python-object: __slots__How do you define a class at runtime with
type(...)? → basic/python-object: Declare Class with type()What are abstract base classes, and how does
abcenforce them? → basic/python-object: Abstract Base ClassesHow do you implement a callable object? → basic/python-object: Callable with __call__
What does
@propertybuy you over plain getters/setters? → basic/python-object: @property Decorator
Concurrency#
What is the GIL, and how does it affect CPU-bound vs I/O-bound code? → concurrency/python-threading: Understanding the GIL
Threading vs multiprocessing — when would you reach for each? → concurrency/python-threading: Creating Threads · multiprocessing: Creating Processes
LockvsRLock— what is the difference? → concurrency/python-threading: Lock · RLockHow do you synchronize with
Event,Condition, orBarrier? → concurrency/python-threading: Event · Condition · BarrierHow would you build a producer-consumer pipeline with
queue.Queue? → concurrency/python-threading: Producer-Consumer with QueueWhat is a deadlock, and how do you prevent one? → concurrency/python-threading: Deadlock Example and Prevention
How do you share state across processes (Queue, Pipe, Value, Manager)? → concurrency/python-multiprocessing: Sharing Data with Queue · Shared Memory · Manager
ThreadPoolExecutorvsProcessPoolExecutor— how do you pick? → concurrency/python-futures: ThreadPoolExecutor · ProcessPoolExecutorHow do you process results from many futures as they complete? → concurrency/python-futures: as_completed
Asyncio#
What actually happens when you call
asyncio.run(coro())? → asyncio/python-asyncio-basic: asyncio.runasyncio.create_taskvs awaiting a coroutine directly — what is the difference? → asyncio/python-asyncio-basic: TasksHow do
asyncio.gatherandasyncio.waitdiffer? → asyncio/python-asyncio-basic: gather · wait for first completedHow do you time-bound an awaitable? → asyncio/python-asyncio-basic: Waiting with Timeout
What is an async context manager, and how do you write one? → asyncio/python-asyncio-basic: Async Context Managers · @asynccontextmanager
How do you call blocking code from an async function without blocking the loop? → asyncio/python-asyncio-basic: Running Blocking Code in Executor
How do you handle exceptions raised inside tasks? → asyncio/python-asyncio-basic: Exception Handling in Tasks
How do you rate-limit concurrency in asyncio? → asyncio/python-asyncio-advanced: Semaphores
What is a graceful shutdown in asyncio? → asyncio/python-asyncio-advanced: Graceful Shutdown
Conceptually, what is a coroutine and how does the event loop drive it? → asyncio/python-asyncio-guide: What is a Coroutine? · Event Loop
Common Gotchas#
Why is using a mutable default argument (
def f(x=[])) dangerous? → basic/python-func: Default Arguments
C Extensions & Interop#
How do you write a C extension module with the CPython C API? → extension/python-capi: Simple C Extension · Parse Arguments
How and why do you release the GIL in a C extension? → extension/python-capi: Release the GIL
How do you call into a shared library with
ctypes? → extension/python-ctypes: Loading Shared Libraries · Basic Type Mapping
Networking#
How do you resolve a hostname to an IP in Python? → network/python-socket: Address Info (DNS Resolution)
Network byte order — when and why do you need
htons/ntohs? → network/python-socket: Network Byte Order ConversionHow do you build a minimal TLS echo server and client? → network/python-socket-ssl: Simple TLS Echo Server · TLS Client
What is mutual TLS (mTLS), and why would a service require it? → network/python-socket-ssl: Mutual TLS (mTLS)
Databases#
What does a SQLAlchemy engine actually hold, and how do connections work? → database/python-sqlalchemy: Create an Engine · Database URL Format
How do you run raw SQL safely with parameters? → database/python-sqlalchemy: Connect and Execute Raw SQL
Transactions in SQLAlchemy — who commits, and when? → database/python-sqlalchemy: Transaction Management
Core vs ORM — what does the ORM add on top? → database/python-sqlalchemy-orm: Declarative Base · Session Basics
Security & Crypto#
What are the common cryptographic mistakes to avoid? → security/python-crypto: Common Mistakes · Security Checklist
Why should you prefer
secretsoverrandomfor tokens? → security/python-crypto: Secure Random Generation · Weak RandomWhat is a timing attack, and how do you defend against one? → security/python-vulnerability: Timing Attacks
How does SQL injection happen in Python, and how is it prevented? → security/python-vulnerability: SQL Injection
See Also#
If a question above is not covered, the top-level indices are the best next stop:
Quick Start — Python core language and data structures
Concurrency — Threading, multiprocessing, futures
Asyncio — Asyncio and async patterns
Network — Sockets and SSL/TLS
Database — SQLAlchemy core and ORM
Security — Cryptography and common vulnerabilities
Extension — C extensions and FFI