python.md
# Python
Core syntax, data structures, and the idioms worth knowing.

## Data structures
```python
xs = [1, 2, 3]                # list  (mutable, ordered)
t  = (1, 2)                   # tuple (immutable)
s  = {1, 2, 3}                # set   (unique)
d  = {"id": 1, "ok": True}    # dict
xs[0], xs[-1], xs[1:3]        # index / negative / slice
d.get("missing", 0)           # safe lookup with default
```

## Strings & f-strings
```python
name = "turtle"
f"hi {name!r}, {3.14159:.2f}" # repr + format spec -> hi 'turtle', 3.14
"a,b,c".split(",")            # -> ['a', 'b', 'c']
" ".join(["a", "b"])          # -> 'a b'
text.strip().lower()          # chainable
```

## Flow & comprehensions
```python
[x*x for x in range(5) if x % 2 == 0]   # list comp -> [0, 4, 16]
{k: v for k, v in pairs}                # dict comp
(x for x in xs)                         # generator (lazy)
for i, v in enumerate(xs): ...
for a, b in zip(xs, ys): ...
value = a if cond else b                # ternary
```

## Functions
```python
def greet(name, *args, greeting="hi", **kwargs):
    return f"{greeting} {name}"
add = lambda a, b: a + b
def square(x: int) -> int:    # type hints
    return x * x
```

## Classes & dataclasses
```python
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int = 0
    def dist(self) -> float:
        return (self.x**2 + self.y**2) ** 0.5

Point(3, 4).dist()            # -> 5.0
```

## Context managers & errors
```python
with open("data.txt") as f:   # file auto-closes
    for line in f:
        process(line)

try:
    risky()
except (ValueError, KeyError) as e:
    log(e)
finally:
    cleanup()
```

## Stdlib worth knowing
```python
from collections import Counter, defaultdict
from itertools import chain, groupby
from pathlib import Path
Path("a/b.txt").read_text()
import json; json.dumps(obj, indent=2)
```

© 2026 anguishedturtle.com