# How to memorize code: a 10-minute drill

> How to memorize code: retype it from memory and grade it by tests. A valid rewrite scored 0.36 similarity and passed; a missing import scored 0.91 and failed.

- Canonical HTML: [https://unrust.dev/blog/how-to-memorize-code](https://unrust.dev/blog/how-to-memorize-code)
- Markdown representation: [https://unrust.dev/blog/how-to-memorize-code/index.md](https://unrust.dev/blog/how-to-memorize-code/index.md)

Published: 2026-11-24. By the Unrust team.

## How do you memorize code? The short answer

To memorize code, retrieve it instead of rereading it: read a snippet once, close it, retype it from memory with autocomplete and AI off, then run tests and diff it against the original. Review after waits of 1, 2, 4 and 8 days, restart at 1 after a miss, and memorize only what you type most weeks.

Memorizing code here means writing it with no example in view. Recognizing code you can see is easier, because the example supplies the cues, and the drill tests the harder skill.

The table is one session of the drill, with planned minutes, not measured ones. The sections below cover how to grade an attempt, six ways a remembered snippet fails with the real error text, what to look up instead, and a review rule you can run by hand.

We ran every program in this post on eight CPython builds (3.9.25 to 3.15.2) and four Node.js builds (18.20.4 to 24.11.0) on November 24, 2026. The output shown comes from CPython 3.11.2 and Node.js 24.11.0, and the text says where other builds differ.

```text
Step  Do this                                                     Plan
----  ----------------------------------------------------------  -----
1     Read one 5 to 10 line snippet once, then close it           1 min
2     Retype it from memory with autocomplete, AI and search off  4 min
3     Run the tests, then diff against the original               3 min
4     Write the first difference in one line                      1 min
5     Put the next review on your calendar                        1 min
```

## How do you memorize syntax without just rereading it?

Write it from memory instead of rereading it: close the snippet, open an empty file with autocomplete and AI off, type the whole function, then run tests. Rereading mostly checks that you recognize the code. Writing it shows what you can produce and exactly which line you could not.

To remember programming syntax, pick a snippet of 5 to 10 lines that you type most weeks. The one below groups items by a key, in Python and in JavaScript, and every run in this post uses it. TypeScript readers can use the JavaScript version.

Write the tests once, before your first attempt, because the tests are the grade: a normal case, an empty input and a second kind of data. They sit outside the 10 minutes, and every review reuses them. The next section shows why you should not grade by comparing text.

```text
# group_by.py
from collections import defaultdict


def group_by(items, key):
    groups = defaultdict(list)
    for item in items:
        groups[key(item)].append(item)
    return dict(groups)

// groupBy.js
function groupBy(items, keyFn) {
  const groups = {};
  for (const item of items) {
    const key = keyFn(item);
    (groups[key] ??= []).push(item);
  }
  return groups;
}

module.exports = { groupBy };
```

## How do you grade a from-memory attempt?

Grade it with tests, and use the diff only to find the first difference. Text similarity measures how close you typed to the original, not whether the code works. In our six Python attempts, a valid rewrite scored 0.36 and passed, while a missing import scored 0.91 and failed.

The grader below runs three tests and prints a line-similarity number from Python's difflib. That number is a simple heuristic on one six-line function, not a benchmark.

Save your attempt next to group_by.py and run python3 grade.py attempt.py. If the tests fail, read the error before you read the diff.

```python
# grade.py
import difflib
import sys
from pathlib import Path

TESTS = [
    ("odd/even", [1, 2, 3, 4, 5], lambda n: n % 2, {1: [1, 3, 5], 0: [2, 4]}),
    ("empty", [], len, {}),
    ("by length", ["a", "bb", "cc", "d"], len, {1: ["a", "d"], 2: ["bb", "cc"]}),
]


def lines(path):
    return [ln.strip() for ln in Path(path).read_text().splitlines() if ln.strip()]


def behavior(path):
    namespace = {}
    try:
        code = compile(Path(path).read_text(), Path(path).name, "exec")
        exec(code, namespace)
        for name, items, key, want in TESTS:
            got = namespace["group_by"](items, key)
            if got != want:
                return f"FAIL wrong result, no error: {name} gave {got}"
    except Exception as exc:
        return f"FAIL {type(exc).__name__}: {exc}"
    return "PASS"


width = max(len(path) for path in sys.argv[1:]) + 2
print(f"{'attempt':<{width}}{'similarity':<12}result")
for path in sys.argv[1:]:
    ratio = difflib.SequenceMatcher(None, lines("group_by.py"), lines(path)).ratio()
    print(f"{path:<{width}}{ratio:<12.2f}{behavior(path)}")
```

## Predict the result: which of six attempts pass the tests?

The six attempts below are ours, one plausible from-memory slip each, not data from learners. The lines show how each differs from group_by.py: a minus is the original line and a plus is what the attempt wrote.

Predict first: which attempts pass the tests, which one has the highest similarity, and which one fails without an error message?

```text
a_setdefault.py
-from collections import defaultdict
-    groups = defaultdict(list)
+    groups = {}
-        groups[key(item)].append(item)
-    return dict(groups)
+        groups.setdefault(key(item), []).append(item)
+    return groups

b_no_import.py
-from collections import defaultdict

c_missing_colon.py
-    for item in items:
+    for item in items

d_plain_dict.py
-from collections import defaultdict
-    groups = defaultdict(list)
+    groups = {}
-    return dict(groups)
+    return groups

e_overwrite.py
-        groups[key(item)].append(item)
+        groups[key(item)] = [item]

f_push.py
-        groups[key(item)].append(item)
+        groups[key(item)].push(item)
```

### Answer and explanation

Only a_setdefault.py passes, and it has the lowest similarity, 0.36, because it uses setdefault instead of defaultdict and changes four of the six lines. The highest score, 0.91, belongs to b_no_import.py, which deleted one line, the import, and fails with a NameError.

e_overwrite.py also scores 0.83 and raises no error. It assigns [item] where the original appends, so each key keeps only its last item and odd/even returns {1: [5], 0: [4]}. Only a test that knows the expected answer notices.

Ranked by text, the one correct attempt comes last and the missing import comes first. Ranked by behavior, the order is clear: one pass, four attempts that stop with an error naming the problem, and one silent wrong answer.

```text
$ python3 grade.py attempts/*.py
attempt                      similarity  result
attempts/a_setdefault.py     0.36        PASS
attempts/b_no_import.py      0.91        FAIL NameError: name 'defaultdict' is not defined
attempts/c_missing_colon.py  0.83        FAIL SyntaxError: expected ':' (c_missing_colon.py, line 6)
attempts/d_plain_dict.py     0.55        FAIL KeyError: 1
attempts/e_overwrite.py      0.83        FAIL wrong result, no error: odd/even gave {1: [5], 0: [4]}
attempts/f_push.py           0.83        FAIL AttributeError: 'list' object has no attribute 'push'

CPython 3.9.25 prints one different line:
attempts/c_missing_colon.py  0.83        FAIL SyntaxError: invalid syntax (c_missing_colon.py, line 6)
```

## Why does code you remember still fail?

In our examples, remembered code failed in six ways: a missing name, a syntax slip, a logic gap, a method from another language, a silent wrong answer, and an API the runtime lacks. Five stop with an error that names the line. One runs clean with wrong data, so only a test with a known answer catches it.

The table gives the error class each runtime raised for each kind. The full Python messages are in the results above, and the JavaScript ones, from a grader with the same three tests, follow the table.

Python 3.9 words the syntax error as invalid syntax instead of expected ':', and Node.js 18.20.4 lacks Object.groupBy. Every other result was identical on all builds.

Log each miss as a short label with the date, such as import, colon, initial list, wrong method, overwrite or version. A label that repeats is what to practice next.

```text
Kind of miss                Python raises   Node.js raises  What you see
--------------------------  --------------  --------------  -------------------------------
1  Missing name             NameError       ReferenceError  an error at the line
2  Syntax slip              SyntaxError     SyntaxError     an error before any code runs
3  Logic gap                KeyError        TypeError       an error at the line
4  Other language's method  AttributeError  TypeError       an error at the line
5  Silent wrong answer      nothing         nothing         wrong data and no error
6  API your runtime lacks   AttributeError  TypeError       an error on older runtimes only

$ node grade.js attempts_js/*.js
attempt                          result
attempts_js/a_reduce.js          PASS
attempts_js/b_lodash.js          FAIL ReferenceError: _ is not defined
attempts_js/c_missing_paren.js   FAIL SyntaxError: Unexpected token '{'
attempts_js/d_undefined_push.js  FAIL TypeError: Cannot read properties of undefined (reading 'push')
attempts_js/e_append.js          FAIL TypeError: groups[key].append is not a function
attempts_js/f_for_in.js          FAIL wrong result, no error: odd/even gave {"0":["0","2","4"],"1":["1","3"]}
attempts_js/g_object_groupby.js  PASS

Node.js 18.20.4 prints one different line:
attempts_js/g_object_groupby.js  FAIL TypeError: Object.groupBy is not a function
```

## Which habits from another language trip you up?

The costly ones run without an error. In Python, str.replace matches plain text, so a regex pattern passed to it usually changes nothing, and list.sort() returns None. In JavaScript, replace with a string replaces only the first match, and sort() orders numbers as text, so [10, 9, 1] becomes [1, 10, 9].

The loud slips are cheaper: join lives on the separator string in Python and on the array in JavaScript, so the wrong one stops at once with an AttributeError or a TypeError.

The programs below print what each line returns, so a silent slip is visible. Memorize the trap, then write the test that would have caught it.

```text
# slips.py
items = ["a", "b", "c"]
nums = [10, 9, 1]


def show(label, thunk):
    try:
        print(f"{label:<34}-> {thunk()!r}")
    except Exception as exc:
        print(f"{label:<34}-> {type(exc).__name__}: {exc}")


show("items.join(', ')", lambda: items.join(", "))
show("', '.join(items)", lambda: ", ".join(items))
show("'a-b-c'.replace('-', '+')", lambda: "a-b-c".replace("-", "+"))
show(r"'room 42'.replace(r'\d+', '#')", lambda: "room 42".replace(r"\d+", "#"))
show("nums.sort()", lambda: nums.sort())
show("sorted([10, 9, 1])", lambda: sorted([10, 9, 1]))

$ python3 slips.py
items.join(', ')                  -> AttributeError: 'list' object has no attribute 'join'
', '.join(items)                  -> 'a, b, c'
'a-b-c'.replace('-', '+')         -> 'a+b+c'
'room 42'.replace(r'\d+', '#')    -> 'room 42'
nums.sort()                       -> None
sorted([10, 9, 1])                -> [1, 9, 10]

// slips.js
const { inspect } = require("node:util");

const items = ["a", "b", "c"];

function show(label, thunk) {
  try {
    console.log(label.padEnd(36) + "-> " + inspect(thunk()));
  } catch (error) {
    console.log(label.padEnd(36) + "-> " + error.name + ": " + error.message);
  }
}

show('", ".join(items)', () => ", ".join(items));
show('items.join(", ")', () => items.join(", "));
show('"a-b-c".replace("-", "+")', () => "a-b-c".replace("-", "+"));
show('"a-b-c".replaceAll("-", "+")', () => "a-b-c".replaceAll("-", "+"));
show("[10, 9, 1].sort()", () => [10, 9, 1].sort());
show("[10, 9, 1].sort((a, b) => a - b)", () => [10, 9, 1].sort((a, b) => a - b));

$ node slips.js
", ".join(items)                    -> TypeError: ", ".join is not a function
items.join(", ")                    -> 'a, b, c'
"a-b-c".replace("-", "+")           -> 'a+b-c'
"a-b-c".replaceAll("-", "+")        -> 'a+b+c'
[10, 9, 1].sort()                   -> [ 1, 10, 9 ]
[10, 9, 1].sort((a, b) => a - b)    -> [ 1, 9, 10 ]
```

## Why does remembered code break on another version?

Your memory has no version number, so you can recall an API that your runtime does not have yet. itertools.batched arrived in Python 3.12 and raises AttributeError on 3.9 to 3.11. Object.groupBy is a TypeError on Node.js 18.20.4 and works on 22.11.0 and 24.11.0.

The Python documentation marks itertools.batched as added in version 3.12. Read that note, and check the runtime you ship on, before you trust a remembered call.

Record the runtime version your project targets, so the version you tested is the version you run. The programs below fail only where the API is missing.

```text
# drift.py
import itertools
import sys

print("python", sys.version.split()[0], end="  ")
try:
    print(list(itertools.batched(range(5), 2)))
except AttributeError as exc:
    print(f"AttributeError: {exc}")

// drift.js
process.stdout.write(`node ${process.version}  `);
try {
  console.log(Object.groupBy([1, 2, 3, 4], (n) => (n % 2 ? "odd" : "even")));
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}

Results of both programs, grouped by build:
CPython 3.9.25, 3.10.22, 3.11.2, 3.11.18
  AttributeError: module 'itertools' has no attribute 'batched'
CPython 3.12.16, 3.13.18, 3.14.10, 3.15.2
  [(0, 1), (2, 3), (4,)]
Node.js 18.20.4
  TypeError: Object.groupBy is not a function
Node.js 22.11.0, 22.23.5, 24.11.0
  [Object: null prototype] { odd: [ 1, 3 ], even: [ 2, 4 ] }
```

## What should you memorize and what should you look up?

Memorize what you type most weeks, plus any trap that fails silently. Look up what you type a few times a year, anything that depends on a version, and exact flags or signatures. That split is our rule of thumb, not a measured cut-off, and the table applies it to five kinds of code.

Frequency decides first: a loop, a branch or a function signature you write every week should come out without a lookup. The cost of a slip decides second: a silent trap is worth memorizing because nothing else will warn you.

Looking up a rare call is normal engineering, not a gap in your skill. Unrust's guide to what code recall means draws the same line between patterns you use and calls you look up.

```text
You are about to write                  Decision                   Why
--------------------------------------  -------------------------  ---------------------------------------
a loop, a branch, a function signature  memorize                   typed weekly; a slip is a SyntaxError
a standard-library call you use weekly  memorize                   a slip is a NameError or AttributeError
a call that fails silently              memorize the trap          sort() and replace() return wrong data
a newer API such as batched             look up, note the version  it fails on older runtimes
a flag, a config key, a rare signature  look up                    typed a few times a year
```

## How often should you review a snippet?

Wait 1 day after the first pass, double the wait after each pass (2, 4, then 8 days), and go back to 1 day after a miss. This is our own rule, not an optimum: we did not test it against other schedules, and it does not come from the research below. You can run it by hand.

The script below applies the rule to six sessions with one miss. It prints day numbers counted from your first session, so you can start on any date.

On a review day, retype the same snippet if you need the exact text, for example in a closed-book exam. If you want the pattern, change the names and the test values, as the code recall guide suggests.

```text
# review.py
results = [True, True, False, True, True, True]  # True = pass, False = miss

day, wait = 0, 0
print("session  day  result  next wait  next review")
for number, passed in enumerate(results, start=1):
    wait = wait * 2 if passed and wait else 1
    result = "pass" if passed else "MISS"
    print(f"{number:<9}{day:<5}{result:<8}{str(wait) + ' d':<11}day {day + wait}")
    day += wait

$ python3 review.py
session  day  result  next wait  next review
1        0    pass    1 d        day 1
2        1    pass    2 d        day 3
3        3    MISS    1 d        day 4
4        4    pass    2 d        day 6
5        6    pass    4 d        day 10
6        10   pass    8 d        day 18
```

## What does the research say, and where does it stop?

In studies with students, testing yourself beat rereading for memory after a delay, and practice spread over time also earned a high rating. Neither abstract mentions code, so applying them to a snippet is an analogy that we did not test. Treat the drill as a reasonable bet, not a proven method.

In Roediger and Karpicke's 2006 experiments, students studied prose passages, then either reread them or took free-recall tests. Five minutes later the rereaders recalled more. After 2 days and after 1 week the tested students recalled substantially more, although rereading had made students more confident.

Dunlosky and colleagues reviewed ten learning techniques in 2013. They rated practice testing and distributed practice as high utility and rereading as low utility, and advised practice testing instead of rereading.

Neither abstract reports a test of retyping code, of a 1, 2, 4 and 8 day schedule, or of how long a snippet takes to memorize, and we ran none of those tests.

## Quick answers about memorizing code

Do programmers memorize code? Some of it. Constructs typed every week, such as loops, function signatures and a handful of library calls, become automatic, and the rest gets looked up. Nobody memorizes everything, and looking up a rare call is normal, so use how often you type it as the test.

How do you memorize code for an exam? First find out whether the exam wants the code word for word or a working solution. For word-for-word code, run the drill on the exact snippet with waits of 1, 2, 4 and 8 days. For a spec, practice the pattern with new names each time and grade it with tests.

How long does it take to memorize code? We did not measure it, so we give no number. It depends on the snippet, your experience and how many reviews you run. The plan here is about 10 minutes per session, and the test is whether you can write it from memory, not how many days have passed.

Does autocomplete make you forget syntax? We cannot say from our own data. Autocomplete supplies the next token, so an attempt with it on checks recognition rather than recall. Turn it off for the drill to see what you can write, and use the four-check test in our recovery plan for a wider read.

Should you memorize code with flashcards? Cards suit facts with one fixed form, such as a flag or a shortcut. A card for a function shows the same text each time, so you may learn the card instead of the skill. Retyping the function and running tests checks what a card cannot, and our Anki comparison covers the trade-off.

## References and next steps

[Python documentation: itertools.batched (added in version 3.12)](https://docs.python.org/3/library/itertools.html#itertools.batched)
[Roediger and Karpicke (2006): Test-Enhanced Learning](https://doi.org/10.1111/j.1467-9280.2006.01693.x)
[Dunlosky et al. (2013): Improving Students' Learning With Effective Learning Techniques](https://doi.org/10.1177/1529100612453266)
[Unrust use case: How to regain useful code recall](https://unrust.dev/use-cases/regain-code-recall)
[Unrust blog: Can't code without AI? A 4-week recovery plan](https://unrust.dev/blog/cant-code-without-ai)
[Unrust blog: Why do I understand code but forget how to write it?](https://unrust.dev/blog/understand-code-but-cant-write-it)
[Unrust blog: How do I get back into coding after a long break?](https://unrust.dev/blog/get-back-into-coding-after-a-break)
[Unrust guide: Anki flashcards vs execution-traced coding drills](https://unrust.dev/guides/anki-flashcards-vs-execution-traced-coding-drills)

[What code recall means, and what not to memorize](https://unrust.dev/guides/code-recall/index.md)

## See what you can write with AI off

Take Unrust's free diagnostic with the AI off: a quick warm-up and three short drills, about 14 minutes in one sitting, with no account needed. Its recall skill measures writing the code from memory, with no autocomplete to lean on.

[Take the free diagnostic](https://unrust.dev/diagnostic/index.md)
