Data Types
| Type | Example | Notes |
|---|
str | "hello", 'world' | Immutable |
int | 42, 1_000_000 | Arbitrary precision |
float | 3.14, 1e-3 | |
bool | True, False | Subclass of int |
list | [1, 2, 3] | Mutable, ordered |
tuple | (1, 2) or 1, 2 | Immutable, ordered |
dict | {"a": 1, "b": 2} | Key-value, keys hashable |
set | {1, 2, 3} | Mutable, unique, unordered |
# Type checking
type(x) == int
isinstance(x, (int, float))
Strings
s = "Hello World"
s[0], s[-1], s[1:5], s[::-1] # H, d, ello, dlroW olleH
s.upper(), s.lower(), s.strip(), s.split()
s.replace("old", "new"), s.startswith("He"), s.endswith("ld")
s.join(["a", "b"]) # "a" + s + "b"
f-strings:
f"{name} is {age}"
f"{x:.2f}" # 2 decimal places
f"{n:b}" # binary
f"{obj!r}" # repr()
Comprehensions
# List
[x**2 for x in range(5)] # [0, 1, 4, 9, 16]
[x for x in lst if x > 0]
# Dict
{k: v*2 for k, v in d.items()}
{i: i**2 for i in range(5)}
# Set
{x % 3 for x in range(10)}
# Nested
[[i*j for j in range(3)] for i in range(3)]
Functions
def f(a, b=0, *args, **kwargs):
pass
# *args: tuple of extra positional args
# **kwargs: dict of extra keyword args
# Lambda
lambda x: x * 2
sorted(lst, key=lambda x: x[1])
# Decorator
def deco(f):
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
@deco
def foo(): pass
Classes
class Foo:
def __init__(self, x):
self.x = x
def __str__(self): return f"Foo({self.x})"
def __repr__(self): return f"Foo(x={self.x})"
def __len__(self): return len(self.x)
def __getitem__(self, i): return self.x[i]
class Bar(Foo):
def __init__(self, x, y):
super().__init__(x)
self.y = y
Dataclasses:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
File I/O
# Read
with open("file.txt") as f:
content = f.read()
lines = f.readlines()
# Write
with open("out.txt", "w") as f:
f.write("text\n")
# Modes: r, w, a, r+, rb, wb
Error Handling
try:
risky()
except ValueError as e:
handle(e)
except (TypeError, KeyError):
pass
except Exception:
raise
else:
# runs if no exception
finally:
# always runs
cleanup()
Built-in Functions
| Function | Example |
|---|
map | list(map(str.upper, lst)) |
filter | list(filter(lambda x: x > 0, lst)) |
zip | list(zip(a, b)) β [(a0,b0), (a1,b1), ...] |
enumerate | for i, x in enumerate(lst): |
sorted | sorted(lst, key=fn, reverse=True) |
range | range(5), range(1, 10, 2) |
sum, min, max | sum(lst), min(lst) |
any, all | any(lst), all(lst) |
abs, round, divmod | abs(-1), round(3.5) |
Standard Library
| Module | Common use |
|---|
os | os.getcwd(), os.listdir(), os.environ |
sys | sys.argv, sys.exit(), sys.path |
json | json.loads(s), json.dumps(obj) |
pathlib | Path("a/b").read_text(), .exists(), .glob("*.py") |
datetime | datetime.now(), timedelta(days=1) |
collections | Counter, defaultdict, deque |
itertools | chain, cycle, combinations, permutations |
from pathlib import Path
Path("data.json").read_text()
Path("out").write_text("content")
from collections import Counter, defaultdict
Counter("hello") # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
dd = defaultdict(list)
Type Hints
def greet(name: str) -> str:
return f"Hello, {name}"
def process(items: list[int], config: dict[str, Any] | None = None) -> None:
pass
from typing import Optional, List, Dict, Union, Any, Callable
x: Optional[int] = None
callback: Callable[[int, str], bool]