Scenario: changing one row changes every row
A three-row board is created with [[0] * 2] * 3. Updating board[0][0] appears to change all three rows. There is no thread, database or cache involved; the issue is visible in a tiny single-process example.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Build a diagnosis from evidence
- Compare a repair with its trade-offs
- Test the changed behaviour
Follow the evidence.
A three-row board is created with [[0] * 2] * 3. Updating board[0][0] appears to change all three rows. There is no thread, database or cache involved; the issue is visible in a tiny single-process example.
Observed evidence
- All three row identities compare equal with is.
- The outer list contains three entries, but they point at one inner list.
- Replacing a row is different from changing an element inside it.
Investigation sequence
- Reduce the board to three rows and two columns.
- Compare board[0] is board[1], then inspect what multiplication repeats.
- Construct independent rows and test both values and identity.
Challenge the repair
- Add a regression test that changes a second row and confirms the first is unchanged.
- What changes if each cell is itself a mutable object?
Read the incident, not just the error
When one cell edit appears in several rows, first investigate whether those rows are the same list. Repeated displayed values do not prove independent storage.
Understand first
A board, spreadsheet-like table or seating grid should usually let one row change without changing the others. A tiny reproducible case can explain the fault before you introduce databases, caches or concurrency.
Words you will see
- Symptom
- An observed result, such as three rows changing after one cell assignment.
- Hypothesis
- A testable possible explanation for the symptom.
- Alias
- Another reference to the same mutable object, not another copy.
Separate the observation from a guessed cause
The observation is that assigning board[0][0] affects the values displayed through every row. That does not establish that Python ran the assignment three times. It could also mean that all row positions lead to one row object.
Reduce the problem to three rows and two columns with no external state. If the behavior remains, a distributed cache or race is not needed to explain it. Small examples remove irrelevant explanations; they do not prove that the same cause explains every similar production symptom.
Use identity to distinguish competing explanations
For board = [[0] * 2] * 3, the inner [0] * 2 is evaluated once. The outer repetition then repeats a reference to that row. board[0] is board[1] tests whether two row positions lead to that very same list.
The cell assignment first selects the row at outer position zero, then replaces its first cell. All other references to that row see the change. The outer list still has three entries, but those entries do not give independent mutable ownership.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
board = [[0] * 2] * 3Create one inner row, then repeat its reference three times.
print(board[0] is board[1])Confirm that two apparent rows are the same object.
board[0][0] = 9Change one cell in that shared inner object.
print(board)See the one changed row through all three outer positions.
A three-row board is created with [[0] * 2] * 3. Updating board[0][0] appears to change all three rows. There is no thread, database or cache involved; the issue is visible in a tiny single-process example.
One write, several observation paths
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- BuildOuter entries 0, 1 and 2 all refer to row A.
- Writeboard[0][0] replaces row A's first cell.
- ObserveReading any row entry reaches the same changed row A.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change a different apparent row.
Try: Use board[2][1] = 7 instead.
The second cell looks changed through all row positions because they still share one object.
Inspect more than one pair.
Try: Print board[1] is board[2].
It is True too; the sharing is not limited to the first two positions.
Before you move on
How many mutable row objects were created by [[0] * 2] * 3? How many outer entries are there?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
There is one inner row object and three entries in the outer list. All three entries refer to that one row, so one inner change appears in three displayed positions.
Investigate before changing code
A useful diagnostic test distinguishes equal values from shared identity, then checks whether the proposed repair really separates the mutable boundary.
Understand first
Two initially zero-filled rows look equal both before and after a shallow outer copy. Tests based only on the initial printout can approve a broken repair.
Words you will see
- Equality: ==
- Whether the row values compare equal.
- Identity: is
- Whether the two expressions refer to the same object.
- Mutation test
- An intentional change used to observe which other values also change.
Design an experiment that could disprove the repair
A shallow outer copy changes the outer list's identity, but leaves its row references unchanged. Assert both equal initial values and distinct row identity only when independence is the actual contract. Then change one cell and check a different row.
The test should fail for the suspected wrong implementation. If both the buggy and repaired board satisfy your test, the test has not distinguished the relevant behavior. A reference answer is not useful evidence unless the tempting wrong alternative is also challenged.
Keep the write at the level being investigated
Replacing copied[0] with an entirely new row would edit the outer list and can make a shallow copy appear fully independent. copied[0][0] instead edits the inner row, which exposes the remaining sharing. Those assignments test different ownership levels.
Avoid relying on numeric object addresses or exact memory sizes. The is relationship directly states the identity question and remains enough to explain the bug. A conceptual reference diagram is not a measured heap trace.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
copied = board.copy()Create another outer list with the same inner row references.
print(copied is board)The outer identity differs.
print(copied[0] is board[0])The first inner row is still shared.
copied[0][0] = 9An inner edit remains visible through the original board.
Reduce the board to three rows and two columns. Compare board[0] is board[1], then inspect what multiplication repeats. Construct independent rows and test both values and identity.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Compare the two assignment levels.
Try: Use copied[0] = [9, 0] and print board.
The original remains zero because you replaced only copied's outer entry.
Separate every row in the copy.
Try: Use copied = [row.copy() for row in board].
Now a copied cell edit no longer changes board, although board's own original rows still share internally.
Before you move on
Would copied[0] = [9, 0] expose the same failure as copied[0][0] = 9?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Replacing copied's outer entry does not edit the shared old row. Editing a cell in that old row is the experiment that exposes inner sharing.
A repair you can explain
Create each mutable row separately when the board requires independent row edits. The construction should express that ownership rule directly.
Understand first
A repair is maintainable when the reader can tell why it prevents the failure, rather than memorising one lucky spelling.
Words you will see
- Comprehension
- A list-building expression evaluated once for each supplied iteration.
- range(3)
- Three iterations with values 0, 1 and 2; not three copies of an already-created row.
- Independent rows
- Different mutable list objects for separate rows.
Locate the repeated construction, not just repetition syntax
In [[0] * 2 for _ in range(3)], the inner [0] * 2 expression is evaluated on each iteration. Each evaluation creates a new list. Repeating the immutable integer zero inside each row is safe for these cell replacements.
The underscore is an ordinary variable name used by convention when its value is not needed. It is not special syntax that creates independence. The important fact is that the list-building expression runs separately.
Prove values, identities and behavior
The provided program changes the first cell to 9, asserts that the first two rows are different objects and prints the expected board. A fuller test should also check the third row, other dimensions and empty rows.
The repair changes memory ownership intentionally. A three-by-two board now needs three inner row lists, not one. That is the correct space cost for independently mutable rows; reducing that space by reintroducing aliases would violate the requirement.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
board = [[0] * 2 for _ in range(3)]Build three different two-cell row lists.
board[0][0] = 9Change only the first row's first cell.
assert board[0] is not board[1]Check the specific independence boundary.
print(board)The other rows remain zero.
The comprehension calls the row construction once per iteration. Each inner list has its own identity, so mutating one row leaves the others unchanged.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Increase the number of rows.
Try: Change range(3) to range(4).
Four independent rows are created; only the selected first cell changes.
Create rows with no cells.
Try: Change [0] * 2 to [0] * 0, then remove the cell assignment.
The board has three different empty rows. The removed assignment would otherwise be an invalid index.
Before you move on
Would [row for _ in range(3)] fix sharing if row is one existing list?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. That comprehension evaluates the name row repeatedly and receives the same list each time. The expression must actually construct or copy a row for each iteration.
Reproduce the alias before blaming another subsystem
Start with the three-by-two board from the incident and change only board[0][0]. Seeing all three displayed rows change is enough to reproduce the symptom without threads, database state, or caching. Preserve this minimal example as a failing regression expectation: the first row should contain 9 and the other rows should remain zero. Adding more application infrastructure would obscure the ownership relationship that already explains the failure.
List plausible explanations and choose observations that distinguish them. A rendering bug would show independent underlying rows despite repeated display values; aliasing predicts that board[0] is board[1]. Check identity, not merely equality, because separately created zero-filled rows are equal too. Replacing board[0] with another list tests a different operation from changing an element inside the referenced row, so do not substitute that experiment for the original reproduction.
Trace exactly what repetition copies
Constructing [0] * 2 creates one row containing two references to the integer zero. Wrapping that row and multiplying the outer sequence by three repeats its reference three times. The result has three outer positions but only one inner row object. Mutating the inner row through any outer position changes that one shared object, and each subsequent display follows its reference to the same changed contents.
A shallow copy of the outer board allocates another sequence of references to the same rows, so it leaves the defect intact. Repetition of immutable zero values is harmless here because integer assignment replaces a cell reference rather than mutating zero itself. The distinction matters when cells are dictionaries or lists: even independently constructed rows can contain shared mutable cell objects if the inner construction repeats a single mutable value.
Repair ownership at the level that must be independent
The reference repair uses a comprehension to construct a new row on each of three iterations. Updating the first row now yields the expected board with 9 only in its first cell. This changes allocation intentionally: r independent rows with c cell positions require O(r times c) cell references, rather than one row reused r times. The cost buys the independent mutation behavior demanded by the board contract.
For a board whose cells hold mutable records, create a fresh cell record per position as well as a fresh row per iteration. deepcopy can help when cloning an existing general object graph, but its memoization preserves sharing relationships within that graph; blindly deep-copying an already aliased board is not a reliable way to request independent rows. Decide the desired ownership topology first, then select construction or copying that actually creates it.
Verify mutation boundaries and compare alternatives
Assert both values and identity after repair. Change a second row and confirm that the first remains unchanged, then modify a second column to cover more than one cell. Include an empty board, a single row, and a board with mutable cells if supported. Check the constructor's output before application code receives it; otherwise a later copy may hide the original factory bug while leaving another caller exposed.
An immutable board representation can make accidental mutation impossible, but changes the update API because producing a modified board requires replacement values. Shared rows can also be legitimate when they are immutable and explicitly documented. Choose these alternatives based on update frequency, memory pressure, and consumer expectations, not because sharing is inherently wrong. The bug is a mismatch between promised independent state and the actual reference graph, so verification should target that promise.
Transfer question: After independent rows are created, changing one cell's tags still changes another cell. What additional diagnosis and repair are needed?
Inspect cell identities and the identities of their nested tags lists. Independent rows do not imply independent cells or independent descendants. If each row repeats one dictionary, construct a dictionary for every cell; if fresh dictionaries all receive the same tags list, construct that list inside the cell factory too. Test by appending a tag in one cell and asserting that every other cell is unchanged. Document whether any descendants are deliberately shared. A blanket shallow outer copy cannot repair this ownership depth, and a deep copy is useful only when its graph-sharing semantics match the intended model.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Recreate the repair independently
Add a regression test that changes a second row and confirms the first is unchanged. Start from the symptoms and write your own regression assertion before opening the reference.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: construct independent board rows
Return a rectangular numeric board whose rows can be edited independently.
The contract
- Inputs rows and columns are nonnegative integers.
- Return a list of rows separate zero-filled lists; preserve empty rows when columns is zero.
- Each call returns independent mutable containers; no negative-dimension policy is required by this contract.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- shape and values
assert new_board(3, 2) == [[0, 0], [0, 0], [0, 0]], "Create the requested board"
- no rows
assert new_board(0, 3) == [], "Zero rows means an empty outer list"
- empty rows
board = new_board(3, 0) assert board == [[], [], []] and board[0] is not board[1], "Keep independent empty rows"
- mutation isolation
board = new_board(2, 2) assert board == [[0, 0], [0, 0]], "Start with zero-filled rows" board[0][0] = 9 assert board == [[9, 0], [0, 0]], "A cell edit must not change another row"
- all row identities
board = new_board(3, 1) assert board == [[0], [0], [0]] and len({id(row) for row in board}) == 3, "Every row must be distinct" - separate calls
first = new_board(1, 1) second = new_board(1, 1) assert first == [[0]] and second == [[0]] and first is not second and first[0] is not second[0], "Separate calls own separate rows"
Why does a correct printed shape not prove independent rows?
A repeated shared row can display the same starting values. A mutation/identity test checks the actual ownership promise. Building r by c cells uses O(r*c + r) time and storage, including zero-column rows.
Guided: copy a flat-row board
Protect a supplied board from later cell replacements in its copied rows.
The contract
- Input is a list of lists of integers; rows may have different lengths and may be shared in the input.
- Return equal contents in a new outer list with a separately copied list for every row position.
- Preserve the input; cells are immutable integers, so deeper copying is not requested.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- contents
assert copy_rows([[1, 2], [3]]) == [[1, 2], [3]], "Keep ragged row contents"
- empty board
assert copy_rows([]) == [], "Empty input remains empty"
- empty rows
result = copy_rows([[], []]) assert result == [[], []] and result[0] is not result[1], "Keep independent empty rows"
- original protection
board = [[1], [2]] result = copy_rows(board) assert result == [[1], [2]], "Preserve initial contents" result[0][0] = 8 assert board == [[1], [2]], "Do not edit source rows"
- shared input row
row = [1] result = copy_rows([row, row]) assert result == [[1], [1]] and result[0] is not result[1] and result[0] is not row, "Separate output row positions"
- outer ownership
board = [[1]] result = copy_rows(board) assert result == [[1]] and result is not board and result[0] is not board[0], "Copy both required levels"
Why can a per-row shallow copy meet this particular contract?
Integer cell values cannot be mutated in place. The outer list and each row are the mutable levels we need to separate. For r rows and n total cells, the work and result storage are O(n + r).
Transfer: return an edited board without touching the original
Combine ownership and a targeted change instead of returning an empty board or a copy alone.
The contract
- Input is a list of integer rows, valid nonnegative row/column indexes, and an integer replacement.
- Return equal contents except for that one cell, without modifying the input.
- Every returned row position must be independent of input rows and other returned rows, even if input rows are shared.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- selected cell
assert edited_board([[1, 2], [3, 4]], 0, 1, 9) == [[1, 9], [3, 4]], "Change only the target"
- different row
assert edited_board([[1], [2]], 1, 0, 8) == [[1], [8]], "Use supplied indexes"
- same value
assert edited_board([[1]], 0, 0, 1) == [[1]], "Replacing with an equal value is valid"
- source preserved
board = [[1, 2], [3, 4]] result = edited_board(board, 0, 0, 9) assert result == [[9, 2], [3, 4]] and board == [[1, 2], [3, 4]], "Preserve caller data"
- shared source rows
row = [0, 0] result = edited_board([row, row], 0, 0, 9) assert result == [[9, 0], [0, 0]] and row == [0, 0], "Separate repeated row positions before writing"
- all ownership
board = [[1], [2]] result = edited_board(board, 0, 0, 3) assert result == [[3], [2]] and result is not board and all(a is not b for a in result for b in board) and result[0] is not result[1], "All returned rows must be independent"
Why is this transfer task different from just fixing new_board?
The source now has existing values and possibly shared rows. The solution must preserve those values, separate the declared row positions and apply one targeted change. For n cells in r rows, it uses O(n+r) time and result storage.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneThe underlying mechanism
Sequence repetition copies references into outer positions. A shallow copy preserves the same referenced items, so it does not repair shared nested ownership.
Understand first
This explains why the bug can survive several layers of apparently reasonable copying and why a correct fix must identify the mutable object being changed.
Words you will see
- Reference graph
- Objects and the connections through which other objects or names reach them.
- Shallow copy
- A new outer object with the existing referenced items.
- Recursive copy
- Copying relevant nested objects too; the intended sharing policy still matters.
The same mechanism can produce different-looking symptoms
An outer list can contain the same inner row more than once, and another outer list can contain that row too. A write through any path reaches the same object. Equality displays contents; identity explains which paths observe a mutation.
Copying each row with row.copy() separates flat row containers. If a cell contains another mutable list, that deeper cell value can still be shared. There is no universal safe depth independent of the data model.
Do not confuse shared immutable values with shared mutable containers
Several cells can refer to the integer zero without allowing one integer to be edited through another cell. Replacing a row position with 9 changes the row's reference; it does not mutate zero. A mutable list cell would be a different ownership boundary.
A correct diagnostic states which object is mutated and which owners should observe it. That is more useful than advising deepcopy everywhere, which can copy intended shared objects or fail on resources that need a separate lifecycle.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
print(shared == separate)Both start with equal contents, despite different ownership.
print(shared[0] is shared[1])The original rows are aliases.
print(separate[0] is separate[1])Copied row containers are distinct.
separate[0][0] = 8Only the selected independent row changes.
Sequence repetition repeats references rather than recursively copying nested objects. A shallow outer copy would preserve the shared rows too. Trace object identity separately from displayed equality when diagnosing aliasing.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change a shared row instead.
Try: Write shared[0][0] = 8.
Both original rows change; the independently copied rows do not.
Expose deeper sharing.
Try: Put a list in each cell before copying rows, then append through one copied cell.
The cell list remains shared unless it is separately copied.
Before you move on
If each cell is itself a list, does copying the rows also copy those cell lists?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. A row copy creates new outer cell positions but shares the referenced cell objects. Decide whether those inner lists should also be independent, then copy at that level.
Alternatives and operational trade-offs
A repair should protect the declared ownership boundary with understandable time and space costs. More copying is not automatically more correct.
Understand first
A rectangular numeric board, an arbitrary graph of objects and a shared resource collection need different policies. Choose the simplest operation that actually preserves the caller's promise.
Words you will see
- r / c
- Here r is the number of rows and c is the number of cells per row.
- Copy policy
- Which mutable objects become independent and which deliberately remain shared.
- Transfer test
- A new case that requires applying the ownership rule rather than reproducing one fixture.
Size includes empty rows too
Building r rows with c cell references requires O(r * c + r) work and storage for the outer list, row lists and cells. The extra r term matters when c is zero: [[], [], []] still contains three row objects.
A new outer list alone costs O(r) but cannot meet independent-cell-edit promises if it still shares mutable row lists. A faster wrong algorithm is not an optimisation of the correct contract.
Use deep copying only with an explicit meaning
copy.deepcopy can recursively copy many Python structures while preserving repeated-reference relationships within the copied graph. It does not magically turn one shared row into several independent rows if the source graph deliberately contains aliases.
For a new zero-filled numeric board, direct row construction expresses the requirement better. For an existing board, copying each row may be enough. For custom objects, external resources or intended sharing, decide the contract before choosing a generic copy function.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
copied = deepcopy(original)Copy the graph while retaining its internal repeated-reference relationship.
print(copied[0] is original[0])The copied row is not the original row.
print(copied[0] is copied[1])The two copied row positions still share one copied row.
copied[0][0] = 7The original is protected, but the copied board still does not have independent rows.
Independent row construction is simple for a rectangular board. deepcopy may be appropriate for a general data graph, but can copy more than intended and is not a substitute for deciding ownership. Memory now includes each genuinely independent row.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Start with independent source rows.
Try: Use original = [[0, 0] for _ in range(2)].
Deepcopy now retains independent row relationships too.
Use an explicit flat-row copy.
Try: Replace deepcopy(original) with [row.copy() for row in original].
Separate row evaluation creates independent copied rows for this flat numeric case.
Before you move on
Why is deepcopy of the repeated-row board not the same repair as constructing each row separately?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Deep copying preserves the source's repeated-reference topology inside a new graph. Independent row construction instead changes that topology so each row position has its own mutable row.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.