Memory Efficient Structures
Learn how to reduce memory usage with generators, iterators, __slots__, and streaming patterns so your data handling stays fast and stable.
Memory matters when data becomes big. ## Common memory mistake Building huge lists: ```python nums = [i for i in range(10_000_000)] ``` Better: generator ```python nums = (i for i in range(10_000_000)) print(next(nums)) ``` ## Streaming file lines (classic real-world) ```python def read_lines(path): with open(path, "r") as f: for line in f: yield line.strip() ``` ## __slots__ (reduce per-object memory) ```python class Person: __slots__ = ["name", "age"] def __init__(self, name, age): self.name = name self.age = age ``` ## Graph: list vs generator ```mermaid flowchart LR A[List] --> B[Allocates all values] C[Generator] --> D[Produces one value at a time] ``` ## Remember - generators are best for large sequences - streaming avoids memory spikes - __slots__ helps when creating many objects