Data Types & Literals
| Type | Example |
|---|
int | 42, -7, 0b1010, 0xFF |
float | 3.14, 1e-4, float('inf') |
str | "hi", f"x={x}", r"\n" |
bool | True, False (subclass of int) |
NoneType | None |
bytes | b"data", bytes(4) |
complex | 3+4j |
Collections
| Type | Mutable | Ordered | Unique | Literal |
|---|
list | yes | yes | no | [1, 2] |
tuple | no | yes | no | (1, 2) |
dict | yes | yes (3.7+) | keys | {"a": 1} |
set | yes | no | yes | {1, 2} |
frozenset | no | no | yes | frozenset({1}) |
- Empty set:
set() — NOT {} (that's a dict)
- Dict merge (3.9+):
a | b
Comprehensions
# List
squares = [x**2 for x in range(10) if x % 2 == 0]
# Dict
inv = {v: k for k, v in original.items()}
# Set
unique_lens = {len(w) for w in words}
# Generator (lazy, no brackets)
total = sum(x**2 for x in range(1000))
# Nested
flat = [x for row in matrix for x in row]
Functions & Signatures
def fn(pos, /, normal, *, kw_only, kw_default=1, **kwargs):
...
# / = positional-only before it
# * = keyword-only after it
# *args / **kwargs = variadic
# Lambda
double = lambda x: x * 2
# Walrus operator (3.8+)
if n := len(data):
print(n)
# Unpacking
a, *rest, z = [1, 2, 3, 4, 5]
Common Builtins
| Function | Use |
|---|
enumerate(it) | index + value pairs |
zip(a, b) | parallel iteration |
map(fn, it) | lazy transform |
filter(fn, it) | lazy filter |
sorted(it, key=fn) | returns new sorted list |
any(it) / all(it) | short-circuit bool checks |
isinstance(x, T) | type check (accepts tuple of types) |
getattr(obj, 'k', default) | safe attribute access |
String Operations
s = " Hello, World! "
s.strip() # "Hello, World!"
s.lower() / s.upper()
s.split(", ") # ["Hello", "World! "]
", ".join(["a","b"]) # "a, b"
s.replace("o", "0")
s.startswith("Hello") / s.endswith("!")
f"{42:>10.2f}" # right-align, 2 decimal places
"sub" in s # membership test
Error Handling
try:
result = risky()
except (ValueError, TypeError) as e:
log(e)
except Exception:
raise # re-raise without losing traceback
else:
process(result) # runs only if no exception
finally:
cleanup() # always runs
# Custom exception
class AppError(Exception):
def __init__(self, msg, code):
super().__init__(msg)
self.code = code
Itertools Essentials
from itertools import (
chain, # chain([1,2], [3,4]) -> 1 2 3 4
islice, # islice(gen, 5) -> first 5
groupby, # group sorted iterable by key
product, # cartesian product
combinations, # nCr combos, no repeat
permutations, # nPr, ordered
count, # count(10) -> 10 11 12 ...
cycle, # cycle("AB") -> A B A B ...
)
File & Path I/O
from pathlib import Path
p = Path("data/input.txt")
p.exists() / p.is_file() / p.is_dir()
p.stem # "input"
p.suffix # ".txt"
p.parent # Path("data")
list(p.parent.glob("*.csv"))
# Read / write
text = p.read_text(encoding="utf-8")
p.write_text("content")
# Context manager (large files)
with open(p, "r") as f:
for line in f:
process(line.rstrip())
Decorators & Context Managers
from functools import wraps, lru_cache, partial
from contextlib import contextmanager
# Memoize
@lru_cache(maxsize=128)
def fib(n): return n if n < 2 else fib(n-1)+fib(n-2)
# Custom decorator
def timer(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
t = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__}: {time.perf_counter()-t:.4f}s")
return result
return wrapper
# Custom context manager
@contextmanager
def managed_resource():
r = acquire()
try:
yield r
finally:
release(r)