Scripts versus notebook state
Quick answer
A notebook lets you execute cells independently in a persistent kernel, the process that stores Python variables. This is useful for exploration, but executing cells out of order may leave a variable from an older run. A script normally executes its statements in source order when launched in a fresh Python process. Neither format automatically guarantees reproducibility.
Why an extra execution changes a result
This standalone example deliberately models executing an accumulation cell twice. It is not a real notebook execution. The list holds error values, and append mutates it.
errors = []errors.append(2)print(errors)errors.append(2)print(errors)Expected output:
[2][2, 2]The second append adds another observation even though no new data arrived. A notebook output may then look plausible while containing duplicates.
Rebuild the result on every run
A function that constructs its output from explicit inputs avoids accidental accumulation across repeated calls. This script-like experiment calculates fresh errors each time; the assert statements check expected behavior.
def errors_for(actual, predicted): return [abs(a - p) for a, p in zip(actual, predicted)]
actual = [10, 16]predicted = [12, 12]first = errors_for(actual, predicted)second = errors_for(actual, predicted)assert len(actual) == len(predicted)assert first == second == [2, 4]print(second)Expected output:
[2, 4]For these equal-length inputs the result stays the same. The length check here verifies a fixed fixture; use explicit validation inside a reusable function for arbitrary inputs.
Common mistakes
Do not trust saved notebook output as evidence that current cells run in order. Restart the kernel and run all cells from top to bottom; if a required variable is missing, add its initialization before use. A clean script can still depend on external files or settings, so record those too.
Practice and next steps
Turn the two-cell accumulation into one function and call it twice with the same inputs. For an optional notebook, restart and run all cells; compare with a clean script. The notebook UI itself is not tested in this batch.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scripts versus notebook state — knowledge check
Apply the lesson to small reproducible experiment scenarios.
Why can notebook output differ after rerunning a cell?
What is the result of appending 2 twice to an empty list?
What is a useful notebook reproducibility check?
Which approach avoids repeated accumulation?
Does starting a fresh script guarantee reproducibility?