Python Cheatsheet — Quick Reference
A concise reference for modern Python 3 (3.11+) syntax, built-in types, and the most-used standard library modules — covers about 80% of everyday scenarios.
Python Python 3.11 (LTS-style)
CPython · Multi-paradigm (OOP · functional · procedural) · Dynamic · strong typing · duck typing
Recommended Learning Path
Start by running python3 and using the REPL -> master variables, built-in types, and control flow -> go deeper into functions, classes, and exceptions -> use the standard library for file and network I/O -> understand references and mutability (shallow vs deep copy) -> pick up asyncio, processes, and regex as needed -> finally learn venv/pip/pyproject for engineering workflows. Revisit the FAQ section whenever you hit a pitfall.
1.Hello World & Build Environment
Run Python, the interactive REPL, virtual environments, and package management.
Minimal Program
print writes to the console. Python organizes blocks with indentation — no braces or semicolons.
Ways to Run
python3 runs a script, -c executes a string, -m runs a module. The interactive REPL evaluates immediately.
Virtual Environments
venv isolates project dependencies. After activation, pip installs affect only that environment. Always use a virtual environment per project.
pip Package Management
pip installs, uninstalls, and freezes dependencies. Pin with ==, range with >=,<y.
pyproject.toml
The modern project config: dependencies, build backend, and tool config all live in pyproject.toml.
Shebang Scripts
#!/usr/bin/env python3 makes a script executable. On POSIX, chmod +x it and run it directly with ./script.py.
REPL Interaction
Run python3 to enter the REPL for interactive debugging. _ holds the last result. Call exit() to leave.
__main__ & Modules
if __name__ == '__main__' distinguishes running-as-a-script from being imported. This is the standard idiom.
2.Variables & Type Annotations
Dynamic typing, type annotations, multiple assignment, scope, and the walrus operator.
Assignment & Inference
No variable declarations — assignment creates the binding. Type is inferred dynamically and can change at any time.
Type Annotations
PEP 484 style annotations with a colon to mark variable types. Annotations don't affect runtime — they're hints and enable checking.
Multiple Assignment
Swap with a, b = b, a. Extended unpacking uses *rest. Counts must match.
Constant Conventions
Python has no constant keyword. ALL_CAPS is the convention for module-level constants.
LEGB Scope
Lookup order: Local -> Enclosing -> Global -> Built-in. Assigning in a function requires global or nonlocal.
Walrus Operator
The := operator assigns inside an expression (Python 3.8+). Avoids repeating a computation.
None & Booleans
None means "no value". Test truthiness with if x, not if x == True. Empty containers are falsy.
del & Garbage Collection
del removes a name or a container element. The name becomes unbound and the object's reference count drops by one.
3.Data Types
Built-in types: numeric, boolean, sequence, mapping, and set, plus advanced type annotations.
Numeric Types
int has arbitrary precision, float is IEEE-754, complex for complex numbers. bool is a subclass of int. Division has two semantics.
Booleans & None
True/False are capitalized. None is a singleton. and/or short-circuit and return the deciding operand.
Sequence Types
str/list/tuple are all sequences: indexed, sliced, and iterable. str/tuple are immutable.
Mapping dict
dict stores key/value pairs and preserves insertion order. Keys must be hashable. .get safely fetches a value.
Set Types
set is an unordered, deduplicating collection; frozenset is its immutable variant. Supports union/intersection/difference.
Bytes Types
bytes is immutable, bytearray is mutable. Convert between text and bytes with encode/decode.
Advanced Type Annotations
The typing module: Optional, Union, TypeVar, generic containers. Python 3.10+ supports the | syntax.
Duck Typing
"If it walks like a duck…": care about behavior, not type. typing.Protocol defines structural interfaces.
4.References & Mutability
Python's object reference semantics: mutable/immutable, shallow vs deep copy, and shared reference pitfalls.
Reference Semantics
Variables bind to objects, not boxes. Multiple names can point to the same object. Assignment rebinds, it does not copy.
Mutable vs Immutable
Mutable types can be changed in place: list/dict/set. Immutable: int/str/tuple/frozenset.
Shallow Copy
copy.copy creates a shallow copy: a new outer container, but inner elements are still shared. Slicing a list is also shallow.
Deep Copy
copy.deepcopy copies recursively. Edits to nested mutable structures don't leak across the copy. Watch the cost.
Shared Reference Pitfalls
When references share a mutable object, a mutation is visible everywhere. Argument passing is also by reference.
is vs ==
== compares values; is compares identity (same object). Use is None to compare with None.
Default Argument Pitfall
A mutable default is evaluated once at definition and shared across calls. Use None as a sentinel and create it inside the function.
Interning & Caching
Small ints and short strings are interned for memory savings. Don't rely on is to compare contents.
5.Control Flow
Conditional branches, loops, pattern matching, and comprehensions.
if / elif / else
Indentation delimits blocks. Use elif for multiple conditions. The condition can be any boolean expression.
Pattern Matching
match-case is structured pattern matching (Python 3.10+). Match and destructure by shape.
for Loop
for iterates any iterable. enumerate adds the index, zip runs in parallel, dict.items() yields key/value pairs.
while Loop
while loops while the condition is true. Use break to exit early — and avoid infinite loops.
break & continue
break exits the whole loop; continue skips to the next iteration. The else clause runs when no break occurred.
Comprehensions
List/dict/set comprehensions build collections in a single line — filter with conditions, transform with expressions.
Truthiness
Use if x for truthiness. 0, '', [], and None are falsy. Avoid comparing explicitly to True/False.
Iteration Idioms
itertools provides efficient iteration primitives: groupby, chain, product, and more.
6.Functions
Function definitions, parameter passing, decorators, generators, and closures.
Function Definition
def defines a function with an indented body. return yields a value; omitting it returns None.
Parameter Types
Positional, keyword, and default arguments. A call can mix positional and keyword arguments.
*args & **kwargs
*args collects extra positional args into a tuple; **kwargs collects extra keyword args into a dict.
Lambda
lambda is a single-expression anonymous function, often used as a key for sort/map/filter.
Closures
An inner function captures variables from the enclosing scope. Returning such a function is the closure pattern used in factories.
Decorators
@decorator wraps a function to enhance its behavior without changing its source — useful for timing and logging.
Generators
yield produces values lazily. Generators stream values one at a time — memory-friendly for large sequences.
Functional Tools
map/filter/reduce/sorted for functional style. functools adds partial and other tools.
Recursion
A function that calls itself — always with a base case. CPython caps depth near 1000 (tweakable via sys.setrecursionlimit).
7.Strings
Immutable str, f-string formatting, common methods, and encoding.
String Basics
Strings are created with single, double, or triple quotes. Escape sequences apply. str is immutable — operations return new strings.
Common Methods
upper/lower for case, strip for whitespace, split/join for splitting and joining, startswith for prefix checks.
f-string Formatting
f"{var}" interpolates expressions. Specs control alignment, precision, and thousands separators. Python 3.12+ allows reusing quotes.
format & % Formatting
str.format uses positional/named placeholders. The % operator is the legacy style. Prefer f-strings for new code.
Split & Join
split on a separator, rsplit from the right, partition into a 3-tuple, join for efficient concatenation.
Strip & Pad
strip/lstrip/rstrip trim whitespace. zfill zero-pads, center aligns, removeprefix/removesuffix strip known strings (3.9+).
Unicode & Encoding
Python str is a sequence of Unicode code points. encode to bytes, decode back. len counts code points.
Search & Replace
find/index locate substrings, replace substitutes, translate maps a translation table, count tallies occurrences.
Text Wrapping
textwrap formats text: wrap to a width, dedent common leading whitespace, fill to a paragraph.
8.Collections & Containers
list/dict/set/tuple operations, the collections module, and sorting.
List Operations
append to the tail, insert anywhere, remove by value, pop the tail or an index, index to find, count to tally.
Dict Operations
Fetch with .get, merge with update or |, iterate items, sort by key/value, and drill into nested dicts.
Set Operations
Union |, intersection &, difference -, symmetric difference ^. Membership test is O(1). Great for dedup.
Tuple Usage
tuple is an immutable sequence — handy for multiple return values, records, and dict keys. namedtuple is a typed variant.
collections Utilities
Counter for tallies, deque for double-ended queues, defaultdict for missing-key defaults, OrderedDict for ordered mappings.
Sorting
sorted returns a new list; list.sort sorts in place. Provide a key callable. Set reverse=True to flip the order.
Slicing
seq[start:stop:step] slices. Negative indices count from the end. Reverse with step -1, copy with [:].
Heaps & Queues
heapq implements heaps; queue provides thread-safe queues — including priority queues.
9.Memory & Performance
Garbage collection, reference counting, memory tools, and performance tuning.
Garbage Collection
Reference counting handles most reclamation; a generational GC breaks reference cycles. No manual free needed.
memoryview & Zero-Copy
memoryview exposes a buffer without copying — efficient for large binary data.
Weak References
weakref.ref does not keep its referent alive. Useful for caches of large objects and for breaking reference cycles.
__slots__ for Memory
__slots__ declares fixed attributes and removes per-instance __dict__ — saving memory and speeding access for millions of instances.
Large-Data Processing
Process large data in chunks, iterate lazily, and never load it all at once. Stream files line by line.
Profiling
cProfile profiles by function and call count; timeit runs micro-benchmarks. Profile before optimizing.
Performance Tips
Locals beat globals, comprehensions beat loops, set lookups are O(1). Don't recompute in tight loops.
Common Memory Errors
MemoryError for out-of-memory, RecursionError for stack blow-ups, and reference cycles — diagnostic tools included.
10.Classes & Objects
class definition, inheritance, dunder methods, dataclass, and enum.
Class Basics
class defines a type. __init__ initializes instances. self refers to the instance; instance methods bind to it.
Attribute Access
Instance attrs shadow class attrs. setattr/getattr/hasattr do dynamic access. property turns a method into a computed attribute.
Three Kinds of Methods
Instance methods take self, class methods take cls, static methods take neither. Decorate with @staticmethod/@classmethod.
Inheritance
A subclass inherits methods from its parent. super() reaches the parent. Override methods as needed. Multiple inheritance follows MRO.
Dunder Methods
Dunder methods customize built-in behavior: __repr__ for display, __eq__ for comparison, __len__ for length, __add__ for +.
dataclass
@dataclass auto-generates __init__, __repr__, __eq__, and more — a declarative way to write data classes.
Enum
Enum defines a set of named constants. Supports str enums, auto numbering, and iteration. Replaces magic numbers.
Context Managers
with manages resources. Implement __enter__/__exit__, or use @contextlib.contextmanager to write one as a generator.
11.Exception Handling
try-except, exception hierarchy, custom exceptions, and the with statement for resource management.
try / except
Catch and handle errors. except filters by type. Use as e to grab the exception object.
else & finally
else runs only when no exception was raised. finally runs no matter what — perfect for cleanup.
Exception Hierarchy
Exception is the base for most errors. Common ones: ValueError, TypeError, KeyError, IndexError.
Custom Exceptions
Subclass Exception to define domain errors. Add fields and messages. Callers catch by type.
raise & Chaining
raise throws deliberately. raise ... from ... chains the cause. A bare raise inside except re-throws the current exception.
assert
assert checks invariants during development. Running with -O strips asserts — never use them for input validation.
Exceptions & Logging
Use logging to capture exceptions with stack traces. logger.exception in an except block records the full traceback.
Error Handling Patterns
EAFP ("easier to ask forgiveness than permission") vs LBYL ("look before you leap"). Prefer guard clauses for early returns.
12.Input / Output
print/input, file I/O, pathlib, JSON/CSV, and standard streams.
Output & Input
print accepts many args with sep/end control. input reads one line as str. Format outputs with f-strings.
File Read/Write
open modes: r read, w write, a append, b binary. read/readline/readlines for reading.
with & Files
with closes the file automatically — even on exceptions. The idiomatic way to read a file.
pathlib Paths
Path provides cross-platform paths with /, exists, mkdir, read_text, etc. The modern replacement for os.path.
JSON Read/Write
json.loads/dumps serialize. Convert dict/list to/from JSON. Pass ensure_ascii=False to keep non-ASCII characters readable.
CSV Read/Write
The csv module handles comma-separated values. writer writes, reader and DictReader read.
Standard Streams
sys.stdin/stdout/stderr handle pipe data. Read line by line from stdin.
Binary I/O
Binary mode reads and writes bytes. struct packs and unpacks. seek/tell provide random access.
13.Common Pitfalls
The most common pitfalls in everyday Python development and the correct idioms.
Mutable Default Argument
A mutable default is created once and shared across calls. Use None as a sentinel.
is vs == Confusion
is compares identity, == compares values. Small ints / short strings may be interned — never use is for content.
Loop Closure Pitfall
A lambda in a loop captures the loop variable by reference (late binding). Bind the current value if you need it now.
String Concatenation
Loop + concat is O(n^2). Collect into a list and join — or build with io.StringIO for huge inputs.
Mutating a List While Iterating
Mutating a list while iterating it skips/repeats elements. Iterate over a copy, or build a new list.
Shadowing Built-ins
Naming a variable after a built-in shadows it. Avoid overwriting list, str, input, sum, etc.
Swallowing Exceptions
A bare except catches everything — including KeyboardInterrupt. Narrow it to specific types, or at least log it.
Misusing Globals
Assigning to a global inside a function creates a local. Add global to rebind it.
Copy & Sort
list.sort sorts in place; sorted returns a new list. Shared references can lead to accidental mutation.
14.Concurrency & Async
threading, asyncio, the GIL, and choosing the right concurrency model.
Thread Basics
threading.Thread creates a thread. start launches it, join waits, daemon=True makes it a background thread.
Thread Class
Subclass Thread and override run. Use locks to share data safely — a clean way to package worker threads.
Locks & Synchronization
Lock guards shared state. with lock acquires and releases automatically. RLock is reentrant.
GIL & Parallelism
CPython's GIL prevents CPU-bound threading from going parallel. Threads still help when the workload is I/O-bound.
Multiprocessing
multiprocessing parallelizes CPU-bound work with a process pool. ProcessPoolExecutor is the high-level wrapper.
asyncio Basics
async def defines a coroutine, await suspends it, asyncio.run drives the event loop.
async / await
async declares a coroutine. await waits on a result. gather runs coroutines in parallel. asyncio.timeout sets deadlines.
Async I/O
aiohttp / httpx make async HTTP requests. For very high-throughput I/O, async wins handily.
Executors
ThreadPoolExecutor pools threads; ProcessPoolExecutor pools processes. Both expose submit() and map().
15.Networking & Modules
Module system, HTTP requests, URL handling, and servers.
Modules & Imports
import loads a module. from x import y pulls specific names. A package is a directory with an __init__.py.
HTTP Requests
The requests library: GET/POST, query params, headers, JSON bodies, response status.
urllib Standard Library
urllib.request makes HTTP requests without third-party libs. urllib.parse splits URLs.
Simple HTTP Server
http.server serves static files or quick prototypes. Subclass BaseHTTPRequestHandler to customize.
Socket Networking
socket provides raw TCP/UDP. Hand-roll protocols or inspect traffic here.
URLs & Parameters
urlparse parses URLs, urlencode builds query strings, quote percent-encodes, urljoin resolves relative paths.
Config & Environment
os.environ exposes environment variables; python-dotenv loads a .env file. Keep config layered.
API Call Patterns
Wrap requests with retries and rate limiting. Validate responses with pydantic for typed data.
16.Date & Time
datetime, formatting, timedeltas, and time zones.
datetime Basics
datetime construction, date/time subclasses, attribute access, and comparison.
Format & Parse
strftime formats, strptime parses. Codes: %Y year, %m month, %d day, %H hour.
timedelta
timedelta expresses duration. Add/subtract days and hours. Compute differences between dates.
Time Zones
timezone handles fixed offsets; zoneinfo (3.9+) loads IANA names. Store in UTC, render in local.
Timestamps
Timestamps are Unix seconds. Convert with timestamp()/fromtimestamp(). Ideal for storage and comparison.
Timing & Sleeping
time.sleep pauses, time.perf_counter measures. For cron-style jobs use the schedule library.
Date Utilities
Weekday detection, month start/end, relative dates, date ranges. The calendar module helps.
Time Interval Checks
Check whether a time falls in a window, detect overlapping intervals, compute remaining time.
17.Processes & System
subprocess, the sys/os modules, command-line arguments, and signals.
subprocess
subprocess.run launches external commands. Capture output, check the return code, and set a timeout.
sys Module
sys.argv holds CLI arguments, sys.exit sets the exit code, sys.path the module search path.
os Module
os covers environment, paths, and directory operations. os.getcwd for the current directory, os.mkdir to create one.
argparse
argparse parses arguments, generates help, supports defaults. The standard way to write CLI tools.
Exit Codes
0 means success, non-zero failure. CI/scripts rely on exit codes. An unhandled exception exits with 1.
Files & Processes
Large file handling, file locks, temp files, atomic writes.
Signal Handling
signal handles Ctrl+C and SIGTERM for graceful shutdown. POSIX mainly — Windows has limited support.
Daemons & Backgrounding
Run in the background, rotate logs, supervise with supervisor or systemd.
18.Regular Expressions & Text
The re module: matching, searching, replacing, groups, and compilation.
match & search
re.match anchors at the start; re.search scans the whole string. Returns a Match or None.
findall & finditer
findall returns all matches as a list. finditer yields them one at a time (memory-friendly for large inputs).
sub Replacement
re.sub performs regex replacement. Backreferences \1 … \9 in the replacement; pass a function for dynamic logic.
split
re.split cuts on a regex. Supports multiple delimiters, retains captures, and caps splits.
Groups
() captures; (?P<name>) names a group; (?:) groups without capturing; | alternation.
Flags
re.I case-insensitive, re.M multiline anchors, re.S dot matches newlines, re.X verbose.
Common Patterns
Common regex snippets for email, phone, URL, IP, Chinese, etc. Validate business formats.
Regex Performance
Precompile patterns, avoid catastrophic backtracking (nested quantifiers), and bound widths. Process big text in chunks.
19.Build & Engineering
Dependency management, virtual environments, testing, linting, and CI.
requirements.txt
Pin versions with pip freeze -> requirements.txt. pip install -r installs. Lock for reproducibility.
venv in Practice
Best practices: one venv per project, never commit it, recreate on broken dependency trees.
Modern Package Managers
uv for blazing-fast installs; poetry for dependency + packaging. Lock files make builds reproducible.
Testing with pytest
Name tests test_* and use assert. fixtures share setup, parametrize runs over inputs.
unittest Standard Library
The stdlib testing framework. Subclass TestCase, use assertXxx methods, override setUp/tearDown.
Lint & Formatting
ruff for fast lint + format, black for style, mypy for types. Pin the rules in pyproject.toml.
Packaging & Publishing
Configure packaging in pyproject.toml, build sdist + wheel, publish to PyPI with twine.
CI & Deployment
Pipeline stages: lint, type-check, test, build. Configure in GitHub Actions.
About this Cheatsheet
This page is a self-contained cheatsheet for Python 3.11, covering the language core and the standard library for about 80% of everyday real-world use. It leans toward modern idioms: f-strings, list comprehensions, generators, context managers, type annotations, dataclass, plus practical modules like collections, itertools, and pathlib. Python was released by Guido van Rossum in 1991, and is known for its readable syntax and "batteries-included" standard library. It is widely used in data analysis, machine learning, automation scripts, and web development (Django / FastAPI). The 19 sections each focus on one topic: basic syntax, variables, types & reference semantics, control flow, functions, strings, lists & dicts, memory & reference counting, classes & OOP, exception handling, I/O, common pitfalls, concurrency (threads / async), networking, time, processes, regex, and build tooling (pip / venv). Each subsection ships with a short concept intro and a copy-paste-ready code snippet. All code and text render locally in your browser — no data ever leaves your device. The authoritative reference is the official Python documentation.
Version 2.1.0