Arrays: Every Message You Chat Lies in One
Last lesson we locked it in: a data structure = a way of organizing. The first way of organizing is one you feed data into every day — every exchange you have with an AI is, to a program, a message list, and a message list's real form is the plainest way of organizing: a row of numbered cells, called an array. This lesson spreads your chat out on the table, then casually answers an old question: why does it forget when you've talked for a while.
Below is a message list: each message owns a cell, and above the cell is its index (the number, counting from 0 — a programmer habit). Tap “Send a message” and watch where the new one lands; then drag the “Context Window” slider and notice which cells go gray — and which one never does.
[0] is pinned: it's the persona and the rules (“You're a thoughtful assistant”). Toss that, and the AI forgets who it is. So “forgetting” isn't mysticism — it's an array slice: keep system + the latest K messages; everything else never reaches the model.
An array's cells sit tightly packed in memory — no gaps allowed in the middle. That brings a headache: to squeeze a new element into the middle, every element to its right has to shift one slot right to make room. Tap any cell to insert a ⭐ there, watch “Moves”; then tap “Append at the end” and compare.
Signature move: jump straight by index
Want message #3? messages[3] — no counting from the start, one hop. Because cells sit packed, the index is the address — that's O(1), or in plain words “no matter how long the array is, the cost is the same.” For fetch-by-position, the array is the fastest way of organizing, full stop.
Soft spot: middle inserts are expensive
You just moved things yourself. Meet a relative while you're at it: the linked list — middle inserts are cheap (tweak two “who's next” pointers), but you lose jump-by-index; finding the 100th means walking from the head one by one. There's no all-purpose way of organizing, only trade-offs. For chat — “append only, often read in chunks” — arrays win, so the message list uses one.
✅ What this lesson wants to share
- A message list is an array: a row of numbered cells, one message per cell, index from 0
- Index jump O(1): for fetch-by-position, the array is the fastest way of organizing
- Context truncation = array slice: keep system + the latest K messages, “cut the head, keep the tail” — that's why long chats forget
- Middle insert is expensive, end append is cheap: so chat history only grows backward (append-only)
- Every way of organizing is a trade-off: linked lists insert fast in the middle but lose the jump — the scenario picks the structure