Appendix C: Python Quick Reference
A compact reference card for Python 3.10+. This appendix is designed for quick lookup, not teaching -- see Chapter 5 for full explanations. Organized by category for fast navigation.
C.1 Data Types
Built-in Scalar Types
| Type |
Example |
Notes |
int |
42, -7, 0b1010, 0xFF |
Arbitrary precision (no overflow) |
float |
3.14, -0.001, 1e10, float('inf') |
64-bit IEEE 754 double precision |
bool |
True, False |
Subclass of int (True == 1, False == 0) |
complex |
3+4j, complex(3, 4) |
Real and imaginary parts are floats |
NoneType |
None |
Singleton; used for "no value" |
Built-in Collection Types
| Type |
Example |
Mutable |
Ordered |
Duplicates |
list |
[1, 2, 3] |
Yes |
Yes |
Yes |
tuple |
(1, 2, 3) |
No |
Yes |
Yes |
set |
{1, 2, 3} |
Yes |
No |
No |
frozenset |
frozenset({1, 2, 3}) |
No |
No |
No |
dict |
{"a": 1, "b": 2} |
Yes |
Insertion order (3.7+) |
Keys: No; Values: Yes |
str |
"hello", 'world' |
No |
Yes |
Yes |
bytes |
b"hello" |
No |
Yes |
Yes |
bytearray |
bytearray(b"hello") |
Yes |
Yes |
Yes |
Type Conversions
int("42") # 42 (string to int)
int(3.9) # 3 (truncates, does not round)
float("3.14") # 3.14
str(42) # "42"
bool(0) # False (0, "", [], {}, None are falsy)
bool(1) # True (everything else is truthy)
list((1, 2, 3)) # [1, 2, 3] (tuple to list)
tuple([1, 2, 3]) # (1, 2, 3) (list to tuple)
set([1, 2, 2, 3]) # {1, 2, 3} (removes duplicates)
dict([("a", 1)]) # {"a": 1} (list of pairs to dict)
C.2 Operators
Arithmetic Operators
| Operator |
Description |
Example |
Result |
+ |
Addition |
7 + 3 |
10 |
- |
Subtraction |
7 - 3 |
4 |
* |
Multiplication |
7 * 3 |
21 |
/ |
True division |
7 / 3 |
2.333... |
// |
Floor division |
7 // 3 |
2 |
% |
Modulo |
7 % 3 |
1 |
** |
Exponentiation |
7 ** 3 |
343 |
Comparison Operators
| Operator |
Description |
Example |
== |
Equal |
x == y |
!= |
Not equal |
x != y |
< |
Less than |
x < y |
> |
Greater than |
x > y |
<= |
Less than or equal |
x <= y |
>= |
Greater than or equal |
x >= y |
is |
Identity (same object) |
x is None |
is not |
Not same object |
x is not None |
in |
Membership |
x in collection |
not in |
Not a member |
x not in collection |
Logical Operators
| Operator |
Description |
Example |
and |
Logical AND (short-circuits) |
x > 0 and x < 10 |
or |
Logical OR (short-circuits) |
x < 0 or x > 10 |
not |
Logical NOT |
not x |
Assignment Operators
x = 10 # Assignment
x += 5 # x = x + 5
x -= 3 # x = x - 3
x *= 2 # x = x * 2
x /= 4 # x = x / 4
x //= 3 # x = x // 3
x %= 7 # x = x % 7
x **= 2 # x = x ** 2
x |= y # x = x | y (bitwise OR or set union)
x &= y # x = x & y (bitwise AND or set intersection)
Walrus Operator (3.8+)
# Assigns and returns value in a single expression
if (n := len(data)) > 10:
print(f"Too long: {n} elements")
C.3 Control Flow
Conditionals
if condition:
...
elif other_condition:
...
else:
...
# Ternary expression
value = x if condition else y
# Match statement (3.10+)
match command:
case "quit":
sys.exit()
case "hello" | "hi":
print("Hello!")
case str(s) if s.startswith("/"):
handle_path(s)
case _:
print("Unknown command")
Loops
# For loop
for item in iterable:
...
# For loop with index
for i, item in enumerate(iterable, start=0):
...
# While loop
while condition:
...
# Loop control
break # Exit the innermost loop
continue # Skip to the next iteration
else: # Runs if loop completes without break
Common Loop Patterns
# Iterate over dict keys and values
for key, value in my_dict.items():
...
# Iterate over two lists in parallel
for a, b in zip(list1, list2):
...
# Iterate with longest (pad with None)
from itertools import zip_longest
for a, b in zip_longest(list1, list2, fillvalue=0):
...
# Iterate in reverse
for item in reversed(my_list):
...
# Iterate over sorted items
for item in sorted(my_list, key=lambda x: x.name, reverse=False):
...
# Range-based loop
for i in range(start, stop, step): # stop is exclusive
...
C.4 Functions
Function Definition
def function_name(param1: type, param2: type = default) -> return_type:
"""Docstring describing the function."""
return value
# Default arguments (mutable default pitfall)
def append_to(item, target=None): # CORRECT: use None, not []
if target is None:
target = []
target.append(item)
return target
Argument Types
def func(pos_only, /, normal, *, kw_only):
"""pos_only: positional-only (before /)
normal: positional or keyword
kw_only: keyword-only (after *)"""
pass
# *args and **kwargs
def func(*args, **kwargs):
# args is a tuple of positional arguments
# kwargs is a dict of keyword arguments
pass
# Unpacking in calls
func(*my_list) # Unpack list as positional args
func(**my_dict) # Unpack dict as keyword args
Lambda Functions
square = lambda x: x ** 2
add = lambda x, y: x + y
# Common use: sort keys, map/filter
sorted(items, key=lambda x: x.priority)
list(map(lambda x: x * 2, numbers))
list(filter(lambda x: x > 0, numbers))
Decorators
# Using a decorator
@decorator
def func():
pass
# Equivalent to: func = decorator(func)
# Common built-in decorators
@staticmethod # No self parameter
@classmethod # First param is cls, not self
@property # Access method like an attribute
@functools.lru_cache # Memoize results
@functools.wraps # Preserve metadata in custom decorators
@dataclasses.dataclass # Generate __init__, __repr__, etc.
@abc.abstractmethod # Require subclass implementation
C.5 Classes
from dataclasses import dataclass, field
# Standard class
class Animal:
"""A base class for animals."""
class_variable = "shared" # Shared by all instances
def __init__(self, name: str, sound: str):
self.name = name # Instance variable
self._sound = sound # Convention: "private"
def speak(self) -> str:
return f"{self.name} says {self._sound}"
@property
def sound(self) -> str:
return self._sound
@sound.setter
def sound(self, value: str):
self._sound = value
@classmethod
def from_dict(cls, data: dict) -> "Animal":
return cls(data["name"], data["sound"])
@staticmethod
def is_valid_name(name: str) -> bool:
return len(name) > 0
def __repr__(self) -> str:
return f"Animal({self.name!r}, {self._sound!r})"
def __str__(self) -> str:
return self.name
def __eq__(self, other) -> bool:
return isinstance(other, Animal) and self.name == other.name
def __hash__(self) -> int:
return hash(self.name)
# Inheritance
class Dog(Animal):
def __init__(self, name: str, breed: str):
super().__init__(name, "woof")
self.breed = breed
# Dataclass (3.7+): auto-generates __init__, __repr__, __eq__
@dataclass
class Point:
x: float
y: float
label: str = "origin"
tags: list[str] = field(default_factory=list)
def distance_to(self, other: "Point") -> float:
return ((self.x - other.x)**2 + (self.y - other.y)**2) ** 0.5
# Frozen dataclass (immutable, hashable)
@dataclass(frozen=True)
class Color:
r: int
g: int
b: int
Common Dunder (Magic) Methods
| Method |
Purpose |
Invoked By |
__init__ |
Initialize instance |
MyClass() |
__repr__ |
Developer-facing string |
repr(obj) |
__str__ |
User-facing string |
str(obj), print(obj) |
__len__ |
Length |
len(obj) |
__getitem__ |
Index access |
obj[key] |
__setitem__ |
Index assignment |
obj[key] = val |
__contains__ |
Membership test |
item in obj |
__iter__ |
Make iterable |
for x in obj |
__next__ |
Next item |
next(obj) |
__enter__ / __exit__ |
Context manager |
with obj: |
__call__ |
Callable |
obj() |
__eq__ / __lt__ / __gt__ |
Comparison |
==, <, > |
__hash__ |
Hash value |
hash(obj), dict keys, sets |
__add__ / __mul__ |
Arithmetic |
obj + other, obj * other |
C.6 Common Built-in Functions
| Function |
Description |
Example |
print() |
Output to stdout |
print("hello", end="\n") |
len() |
Length of collection |
len([1, 2, 3]) returns 3 |
range() |
Integer sequence |
range(0, 10, 2) gives 0, 2, 4, 6, 8 |
enumerate() |
Index-value pairs |
enumerate(["a", "b"], start=1) |
zip() |
Pair items from iterables |
zip([1, 2], ["a", "b"]) |
map() |
Apply function to each item |
map(str, [1, 2, 3]) |
filter() |
Keep items matching predicate |
filter(None, [0, 1, "", "a"]) |
sorted() |
Return new sorted list |
sorted(data, key=func, reverse=True) |
reversed() |
Reverse iterator |
reversed([1, 2, 3]) |
any() |
True if any element is truthy |
any([False, True, False]) |
all() |
True if all elements are truthy |
all([True, True, True]) |
min() / max() |
Minimum / maximum |
min(3, 1, 2), max(data, key=func) |
sum() |
Sum of numbers |
sum([1, 2, 3], start=0) |
abs() |
Absolute value |
abs(-5) returns 5 |
round() |
Round to n digits |
round(3.14159, 2) returns 3.14 |
isinstance() |
Type check |
isinstance(x, (int, float)) |
type() |
Get type |
type(42) returns <class 'int'> |
hasattr() |
Check attribute existence |
hasattr(obj, "name") |
getattr() |
Get attribute |
getattr(obj, "name", default) |
id() |
Object identity |
id(obj) (memory address in CPython) |
hash() |
Hash value |
hash("hello") |
input() |
Read from stdin |
name = input("Name: ") |
open() |
Open file |
open("file.txt", "r") |
vars() |
Object's __dict__ |
vars(obj) |
dir() |
List of attributes |
dir(obj) |
help() |
Interactive help |
help(str.split) |
C.7 String Methods
s = " Hello, World! "
# Case
s.upper() # " HELLO, WORLD! "
s.lower() # " hello, world! "
s.title() # " Hello, World! "
s.capitalize() # " hello, world! "
s.casefold() # " hello, world! " (aggressive lowercase for comparison)
s.swapcase() # " hELLO, wORLD! "
# Whitespace
s.strip() # "Hello, World!"
s.lstrip() # "Hello, World! "
s.rstrip() # " Hello, World!"
# Search
s.find("World") # 9 (index, or -1 if not found)
s.index("World") # 9 (raises ValueError if not found)
s.rfind("l") # 12 (search from right)
s.count("l") # 3
s.startswith(" H") # True
s.endswith("! ") # True
# Replace and split
s.replace("World", "Python") # " Hello, Python! "
s.split(",") # [" Hello", " World! "]
s.rsplit(" ", 1) # [" Hello, World!", " "]
"a.b.c".split(".", 1) # ["a", "b.c"]
"line1\nline2".splitlines() # ["line1", "line2"]
# Join
", ".join(["a", "b", "c"]) # "a, b, c"
"\n".join(lines)
# Test
"abc123".isalnum() # True
"abc".isalpha() # True
"123".isdigit() # True
" ".isspace() # True
"Hello".istitle() # True
# Format
f"Hello, {name}!" # f-string (preferred)
f"{value:.2f}" # Two decimal places
f"{number:,}" # Thousands separator
f"{text:>20}" # Right-align in 20 chars
f"{text:<20}" # Left-align in 20 chars
f"{text:^20}" # Center in 20 chars
"Hello, {}!".format(name) # .format() method
"Hello, {name}!".format(name="World") # Named placeholders
# Miscellaneous
"hello".center(20, "-") # "-------hello--------"
"hello".zfill(10) # "00000hello"
"hello".encode("utf-8") # b'hello'
b"hello".decode("utf-8") # "hello"
C.8 List Methods
lst = [3, 1, 4, 1, 5]
# Add elements
lst.append(9) # [3, 1, 4, 1, 5, 9]
lst.insert(0, 0) # [0, 3, 1, 4, 1, 5, 9]
lst.extend([2, 6]) # [0, 3, 1, 4, 1, 5, 9, 2, 6]
# Remove elements
lst.remove(1) # Removes first occurrence of 1
lst.pop() # Removes and returns last element
lst.pop(0) # Removes and returns element at index 0
lst.clear() # Removes all elements
# Search
lst.index(4) # Index of first occurrence (raises ValueError)
lst.count(1) # Number of occurrences
# Sort and reverse
lst.sort() # Sort in place (returns None)
lst.sort(key=abs, reverse=True)
lst.reverse() # Reverse in place
# Copy
new_list = lst.copy() # Shallow copy
import copy
deep = copy.deepcopy(lst) # Deep copy (nested objects)
# Slicing
lst[1:4] # Elements at index 1, 2, 3
lst[:3] # First 3 elements
lst[-2:] # Last 2 elements
lst[::2] # Every other element
lst[::-1] # Reversed copy
lst[1:4] = [10, 20] # Replace slice
# List comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in numbers if x % 2 == 0]
flat = [item for sublist in nested for item in sublist]
matrix = [[0] * cols for _ in range(rows)]
C.9 Dictionary Methods
d = {"a": 1, "b": 2, "c": 3}
# Access
d["a"] # 1 (raises KeyError if missing)
d.get("a") # 1
d.get("z", 0) # 0 (default if missing)
d.setdefault("d", 4) # Sets d["d"]=4 if "d" not present, returns value
# Add / update
d["e"] = 5 # Add or overwrite
d.update({"f": 6, "g": 7})
d |= {"h": 8} # Merge update (3.9+)
merged = d | other # Merge into new dict (3.9+)
# Remove
del d["a"] # Remove key (raises KeyError if missing)
d.pop("b") # Remove and return value
d.pop("z", None) # Return None if missing (no error)
d.popitem() # Remove and return last inserted pair
d.clear() # Remove all
# Iterate
d.keys() # View of keys
d.values() # View of values
d.items() # View of (key, value) tuples
for k, v in d.items():
...
# Test
"a" in d # True if key exists
len(d) # Number of key-value pairs
# Dict comprehensions
squares = {x: x**2 for x in range(10)}
filtered = {k: v for k, v in d.items() if v > 1}
inverted = {v: k for k, v in d.items()}
# collections.defaultdict
from collections import defaultdict
word_count = defaultdict(int)
grouped = defaultdict(list)
C.10 Set Methods
s = {1, 2, 3, 4}
t = {3, 4, 5, 6}
# Add / remove
s.add(5) # Add element
s.discard(5) # Remove if present (no error)
s.remove(5) # Remove (raises KeyError if missing)
s.pop() # Remove and return arbitrary element
# Set operations
s | t # Union: {1, 2, 3, 4, 5, 6}
s & t # Intersection: {3, 4}
s - t # Difference: {1, 2}
s ^ t # Symmetric difference: {1, 2, 5, 6}
s.union(t) # Same as s | t
s.intersection(t) # Same as s & t
s.difference(t) # Same as s - t
# Test
s.issubset(t) # True if all elements of s are in t
s.issuperset(t) # True if s contains all elements of t
s.isdisjoint(t) # True if no common elements
# Set comprehension
evens = {x for x in range(20) if x % 2 == 0}
C.11 File Operations
# Reading
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read() # Entire file as string
# or
lines = f.readlines() # List of lines (with \n)
# or
for line in f: # Iterate line by line (memory efficient)
process(line.rstrip("\n"))
# Writing
with open("file.txt", "w", encoding="utf-8") as f:
f.write("Hello\n")
f.writelines(["line1\n", "line2\n"])
# Appending
with open("file.txt", "a", encoding="utf-8") as f:
f.write("New line\n")
# Binary
with open("image.png", "rb") as f:
data = f.read()
# JSON
import json
with open("data.json", "r") as f:
data = json.load(f) # Parse file to Python object
with open("data.json", "w") as f:
json.dump(data, f, indent=2) # Write Python object as JSON
# CSV
import csv
with open("data.csv", "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["column_name"])
# Path handling (preferred over os.path)
from pathlib import Path
p = Path("data") / "subdir" / "file.txt"
p.exists() # True/False
p.is_file() # True if it is a file
p.is_dir() # True if it is a directory
p.parent # Parent directory
p.name # "file.txt"
p.stem # "file"
p.suffix # ".txt"
p.read_text() # Read entire file
p.write_text("content") # Write entire file
p.mkdir(parents=True, exist_ok=True) # Create directories
list(p.parent.glob("*.txt")) # List matching files
list(p.parent.rglob("*.py")) # Recursive glob
C.12 Exception Handling
# Basic try/except
try:
result = int(user_input)
except ValueError:
print("Not a valid integer")
# Multiple exceptions
try:
data = json.loads(text)
except (json.JSONDecodeError, TypeError) as e:
print(f"Parse error: {e}")
# Full try/except/else/finally
try:
f = open("file.txt")
data = f.read()
except FileNotFoundError:
data = "default"
except PermissionError:
raise # Re-raise the exception
else:
print("File read successfully") # Runs only if no exception
finally:
print("Always runs") # Cleanup, runs regardless
# Raising exceptions
raise ValueError("Invalid input: must be positive")
raise TypeError(f"Expected str, got {type(value).__name__}")
# Custom exceptions
class AppError(Exception):
"""Base exception for this application."""
pass
class NotFoundError(AppError):
"""Raised when a resource is not found."""
def __init__(self, resource: str, id: str):
self.resource = resource
self.id = id
super().__init__(f"{resource} with id '{id}' not found")
Common Exception Hierarchy (partial)
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- Exception
+-- StopIteration
+-- ArithmeticError
| +-- ZeroDivisionError
| +-- OverflowError
+-- AttributeError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- OSError
| +-- FileNotFoundError
| +-- FileExistsError
| +-- PermissionError
| +-- IsADirectoryError
+-- TypeError
+-- ValueError
| +-- UnicodeError
+-- RuntimeError
| +-- RecursionError
+-- StopAsyncIteration
+-- ConnectionError
| +-- ConnectionRefusedError
| +-- ConnectionResetError
+-- TimeoutError
C.13 Type Hints
from typing import Optional, Union, Any, Callable, Iterator, Generator
from collections.abc import Sequence, Mapping, Iterable
# Basic types
x: int = 42
name: str = "hello"
values: list[int] = [1, 2, 3] # 3.9+ syntax
mapping: dict[str, int] = {"a": 1} # 3.9+ syntax
coordinates: tuple[float, float] = (1.0, 2.0)
unique: set[str] = {"a", "b"}
# Optional (value or None)
result: int | None = None # 3.10+ syntax
result: Optional[int] = None # Older syntax
# Union types
value: int | str = "hello" # 3.10+ syntax
value: Union[int, str] = "hello" # Older syntax
# Function signatures
def greet(name: str, excited: bool = False) -> str:
...
def process(items: list[str]) -> dict[str, int]:
...
# Callable type
handler: Callable[[int, str], bool] # Takes int and str, returns bool
callback: Callable[..., None] # Any args, returns None
# Generic collections (abstract)
def process(items: Sequence[int]) -> None: ... # list, tuple, etc.
def lookup(data: Mapping[str, int]) -> None: ... # dict, etc.
def consume(items: Iterable[str]) -> None: ... # Any iterable
# TypeAlias (3.10+)
type Point = tuple[float, float] # 3.12+ syntax
Point = tuple[float, float] # Older syntax
# TypeVar for generics
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
# Literal types
from typing import Literal
def set_mode(mode: Literal["read", "write", "append"]) -> None: ...
# TypedDict
from typing import TypedDict
class UserDict(TypedDict):
name: str
age: int
email: str | None
# Protocol (structural typing / duck typing)
from typing import Protocol
class Readable(Protocol):
def read(self) -> str: ...
C.14 Common Standard Library Modules
| Module |
Purpose |
Key Functions/Classes |
os |
OS interface |
os.environ, os.getenv(), os.getcwd() |
sys |
System parameters |
sys.argv, sys.exit(), sys.path, sys.stdin/stdout |
pathlib |
Path manipulation |
Path(), .exists(), .glob(), .read_text() |
json |
JSON encoding/decoding |
json.loads(), json.dumps(), json.load(), json.dump() |
csv |
CSV reading/writing |
csv.reader(), csv.writer(), csv.DictReader() |
re |
Regular expressions |
re.search(), re.match(), re.findall(), re.sub() |
datetime |
Dates and times |
datetime.now(), timedelta, .strftime(), .strptime() |
collections |
Specialized containers |
defaultdict, Counter, deque, namedtuple, OrderedDict |
itertools |
Iterator tools |
chain(), product(), combinations(), groupby(), islice() |
functools |
Higher-order functions |
lru_cache, partial, reduce, wraps, total_ordering |
typing |
Type hints |
Optional, Union, Literal, TypeVar, Protocol |
dataclasses |
Data classes |
@dataclass, field(), asdict(), astuple() |
logging |
Logging |
logging.getLogger(), logging.basicConfig() |
unittest |
Unit testing |
TestCase, assertEqual(), assertRaises() |
argparse |
CLI argument parsing |
ArgumentParser, add_argument(), parse_args() |
subprocess |
Run external commands |
subprocess.run(), subprocess.Popen() |
http |
HTTP support |
http.server, http.client |
urllib |
URL handling |
urllib.parse.urlparse(), urllib.request.urlopen() |
hashlib |
Hash functions |
hashlib.sha256(), hashlib.md5() |
secrets |
Cryptographic randomness |
secrets.token_hex(), secrets.choice() |
random |
Pseudo-random numbers |
random.randint(), random.choice(), random.shuffle() |
math |
Math functions |
math.sqrt(), math.ceil(), math.floor(), math.pi |
statistics |
Basic statistics |
statistics.mean(), statistics.median(), statistics.stdev() |
textwrap |
Text formatting |
textwrap.dedent(), textwrap.wrap(), textwrap.indent() |
shutil |
File operations |
shutil.copy(), shutil.rmtree(), shutil.move() |
tempfile |
Temporary files |
tempfile.NamedTemporaryFile(), tempfile.mkdtemp() |
contextlib |
Context managers |
@contextmanager, suppress(), redirect_stdout() |
abc |
Abstract base classes |
ABC, @abstractmethod |
enum |
Enumerations |
Enum, IntEnum, auto() |
sqlite3 |
SQLite database |
sqlite3.connect(), cursor.execute(), cursor.fetchall() |
C.15 Common Patterns
Guard Clauses
def process(data):
if data is None:
return None
if not data:
return []
# Main logic here
Context Managers
from contextlib import contextmanager
@contextmanager
def timer(label: str):
import time
start = time.perf_counter()
yield
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.3f}s")
with timer("processing"):
do_work()
Generators
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Generator expression
total = sum(x**2 for x in range(1000))
Enum
from enum import Enum, auto
class Status(Enum):
PENDING = auto()
ACTIVE = auto()
CLOSED = auto()
status = Status.ACTIVE
if status == Status.ACTIVE:
...
Unpacking
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
first, *mid, last = [1,2,3,4,5] # first=1, mid=[2,3,4], last=5
(a, b), (c, d) = [(1, 2), (3, 4)]
# Swap
a, b = b, a
# Dict unpacking
defaults = {"color": "blue", "size": 12}
config = {**defaults, "size": 14, "bold": True}
Main Guard
def main():
...
if __name__ == "__main__":
main()