Names, values and identity
Stop thinking of variables as boxes: names refer to objects.
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: 10 minutes; optional deep dive: 8 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.
- Bind and rebind names
- Tell equality from identity
- Predict aliases
Assignment binds a name
Assignment gives a name a reference to a value. Giving that name another value later does not rewrite other names.
Understand first
You often need an old reading and a new reading at the same time. Understanding assignment prevents a later update from seeming to change history.
Words you will see
- Object
- A Python value with a type and identity.
- Binding
- The connection between a name and an object.
- Rebinding
- Changing which object a name refers to.
Read the right side first
In a = 10, Python evaluates the integer expression 10, then binds a to its result. In b = a, the right side reads the object already named a. No instruction here requests a copy. Both names can initially refer to the same integer.
In a = 20, Python changes the binding of a. It does not go searching for every other name that once read a. b still refers to 10. Integers cannot be edited in place, so an arithmetic update such as a += 1 also leaves an earlier integer binding of b unchanged.
Choose names for roles, not storage slots
Use an old_total name when the previous result matters, and calculate a new_total explicitly. Assignment is not an equation that stays true forever and is not a spreadsheet dependency. A name must be bound before it is read; reading a missing name raises NameError.
This example takes a fixed number of small operations. It promises values, not the memory address of either integer. If the result is a mutable container, assignment still follows the same binding rule, but edits to that shared object introduce a second kind of change.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
a = 10Bind a to the integer 10.
b = aRead a and bind b to that same value.
a = 20Rebind a only; b remains bound to 10.
print(a, b)Read the current two bindings and display 20 followed by 10.
The right side is evaluated first. The left name then refers to that result. Assigning b = a does not copy an object. Reassigning a name is different from changing the object it currently refers to.
Conceptual binding changes, not a measured memory layout
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Initial valuea refers to integer 10.
- Another nameb also refers to 10; there is no permanent name-to-name link.
- Rebindinga refers to 20 while b still refers to 10.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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 the last binding.
Try: Replace a = 20 with a = 30.
Only the first printed number becomes 30.
Read after the update.
Try: Move b = a below a = 20.
Now b reads 20, so both printed values are 20.
Before you move on
After x = 4; y = x; x = x + 3, what does y hold, and why?
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
y still holds 4. The addition produces 7 and rebinds x; it never rebinds y or edits the integer 4.
Mutable objects make aliases visible
An alias is another name for the same object. When that object can change, an edit through either name is visible through both.
Understand first
A shopping list may be passed to another part of a program. You need to decide whether that part may update your original list or should work on a copy.
Words you will see
- Mutable
- Able to change in place after creation.
- Alias
- Another reference to the same object.
- Mutation
- An edit to an existing object, rather than a new binding.
Two names, one edit
a = ["tea"] creates one list. b = a does not create another list. b.append("coffee") asks that list to add an item at the end. Reading a then sees the changed list because a and b still reach the same object.
append is a method: an operation reached through the object before the dot. It mutates the list and returns None. a is b asks whether the references reach the identical object, so it prints True here. The result is not based on comparing the spellings of the names.
Decide who owns changes
Aliasing is useful when several parts of a program deliberately share one working list. It is risky when a caller expects its input to stay unchanged. For a flat list of immutable values, a.copy() gives a new outer list you can append to independently.
Rebinding b to a fresh list would not mutate a. In contrast, clearing b would clear the shared list. An empty shared list is still shared, even though its printout contains no items. Test behavior after a change, not only whether the initial displays look alike.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
a = ["tea"]Create a list containing tea.
b = aKeep a second reference to that list.
b.append("coffee")Edit the one shared list.
print(a)Show the changed contents through a.
print(a is b)Confirm that both references still reach the same list.
Lists can change in place. Two names can refer to the same list, so an append through one name is observable through the other.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
Remove the alias.
Try: Replace b = a with b = a.copy().
a stays ['tea'] and the identity test becomes False.
Contrast rebinding.
Try: Replace b.append("coffee") with b = ["coffee"].
a remains ['tea']; b now refers to a different list.
Before you move on
If two names share an empty list and one appends 'rice', what does the other name see?
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
It sees ['rice']. Being empty does not make the list immutable or prevent two names from sharing it.
Use == for values
Equality asks whether values compare equal. Identity asks whether two references reach the very same object.
Understand first
Two independently made lists can contain the same data. Your comparison should reflect whether you care about their contents or about sharing one object.
Words you will see
- Equality (==)
- A comparison defined by the values' types.
- Identity (is)
- Whether two references designate the same object.
- None
- The single built-in value commonly used to mean no result or no supplied value.
Choose the question before the operator
The sample creates two lists containing the string tea. left == right is True because their elements compare equal in order. left is right is False because the two list displays in source create separate lists. Changing either list would not change the other.
Use == for ordinary numbers and text. Python implementations may reuse some immutable objects; a mistaken is comparison can appear to work for one small integer or short string and fail for another. Do not infer a value-comparison rule from that coincidence.
Recognise absence explicitly
value is None is appropriate because None is a singleton: there is one such object. An empty list, zero and an empty string are real values, not automatically absent. Use an explicit None check when those values must remain valid.
Use not value only when your contract intentionally groups all false-valued inputs together. Equality for containers can inspect their elements; identity does not compare contents. Custom classes can define equality differently, so do not generalise this list example into every type's rule.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
left = ["tea"]Create one list.
right = ["tea"]Create a second list with matching contents.
print(left == right)Compare contents and display True.
print(left is right)Compare identity and display False.
print(value is None)Recognise the explicit absence marker.
Use == to ask whether values compare equal. Use is for identity checks such as value is None. Do not use is to compare strings or integers; implementation reuse can make incorrect code appear to work.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
Share the list intentionally.
Try: Replace right = ["tea"] with right = left.
Both list comparisons become True.
Keep zero separate from missing.
Try: Replace value = None with value = 0.
The final identity check becomes False.
Before you move on
A supplied count is 0. Should count is None classify it as absent?
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. Zero is an integer value, not None. Testing is None preserves a valid count of zero.
Where this idea earns its place
Reference semantics matter whenever several functions receive the same mutable object. A shopping basket, configuration dict or list of test records can be changed through a name that looks unrelated to the original caller. The central question is not whether two variables have the same spelling or printed contents, but whether they refer to one object.
Follow the mechanism step by step
For b = a, the right side is evaluated first and the resulting reference is bound to b. No recursive copy is implied. Rebinding b later changes that binding only. Calling b.append changes the list object itself, so a observes the mutation when it still refers to that list. Draw names as arrows and containers as objects to keep these operations separate.
Work through a concrete application
Trace a function that receives a list and appends a value. Record the caller's list before and after the call, then change the function to assign its parameter to a new list. Compare those outcomes. Next create a shallow copy and repeat with a nested list; the new outer list does not make the nested element references independent.
Failure cases and misleading shortcuts
Do not use is as a faster spelling of equality. Integer or string interning may make a mistaken identity comparison appear correct for one value and fail for another. Conversely, equal containers need not be aliases. A diagnostic repr also need not show every identity relationship, so identical printed lists are insufficient evidence of sharing.
Cost, ownership and alternatives
Copying a flat n-element list takes O(n) reference storage and time; rebinding an ordinary name does not copy those elements. Deep copying can traverse a much larger object graph and cannot sensibly duplicate every resource, such as a file handle or lock. Prefer an explicit ownership contract to repeatedly adding copies until a test passes.
Verify the contract
Test both value behaviour and the ownership promise. If a function promises not to mutate input, compare it with a suitable before snapshot after the call. If independent nested state is required, mutate one branch and check the other. Avoid asserting incidental memory addresses or exact collection timing, since those are not portable language contracts.
Transfer question: A function must normalise a caller's nested records without changing them. Is records.copy() enough?
Only if the function replaces outer slots and never mutates shared nested values. If it edits a dict inside each record, shallow copying retains those dict references. Reconstruct the fields you need into independent records, or use a justified deep copy for the supported data graph, and test nested mutation explicitly.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Independent shopping lists
Make an independent shallow copy of the flat list, then add rice only to the copy.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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: extend an independent list
Add an item without changing the caller's flat list.
The contract
- items is a list of strings; item is a string.
- Return a new list containing all original strings in order, followed by item. Keep duplicates.
- Do not mutate items. Empty input still returns a new one-item list.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
- one item
from copy import deepcopy args = (["tea"], "rice") before = deepcopy(args) expected = ["tea", "rice"] result = independent_add(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for one item" assert args == before, "Preserve every supplied input" assert result is not args[0], "Respect nested types and ownership promises"
- empty source
from copy import deepcopy args = ([], "rice") before = deepcopy(args) expected = ["rice"] result = independent_add(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty source" assert args == before, "Preserve every supplied input" assert result is not args[0], "Respect nested types and ownership promises"
- duplicate allowed
from copy import deepcopy args = (["tea"], "tea") before = deepcopy(args) expected = ["tea", "tea"] result = independent_add(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for duplicate allowed" assert args == before, "Preserve every supplied input" assert result is not args[0], "Respect nested types and ownership promises"
- several items
from copy import deepcopy args = (["a", "b"], "c") before = deepcopy(args) expected = ["a", "b", "c"] result = independent_add(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for several items" assert args == before, "Preserve every supplied input" assert result is not args[0], "Respect nested types and ownership promises"
- empty text item
from copy import deepcopy args = (["a"], "") before = deepcopy(args) expected = ["a", ""] result = independent_add(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty text item" assert args == before, "Preserve every supplied input" assert result is not args[0], "Respect nested types and ownership promises"
- repeated source
from copy import deepcopy args = (["x", "x"], "y") before = deepcopy(args) expected = ["x", "x", "y"] result = independent_add(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for repeated source" assert args == before, "Preserve every supplied input" assert result is not args[0], "Respect nested types and ownership promises"
Why is returning items.append(item) wrong twice?
It mutates the caller's list and returns None. A shallow copy is enough for these strings; copying n references takes O(n) work and output space.
Guided: retain the previous reading
Return both the original and updated integer readings.
The contract
- Both inputs are integers, including negative values and zero.
- Return a two-integer tuple (original value, value plus change).
- Do not print, read input or overwrite the original result with the new one.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
- increase
from copy import deepcopy args = (10, 3) before = deepcopy(args) expected = (10, 13) result = old_and_new(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for increase" assert args == before, "Preserve every supplied input" assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
- no change
from copy import deepcopy args = (5, 0) before = deepcopy(args) expected = (5, 5) result = old_and_new(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for no change" assert args == before, "Preserve every supplied input" assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
- decrease
from copy import deepcopy args = (9, -4) before = deepcopy(args) expected = (9, 5) result = old_and_new(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for decrease" assert args == before, "Preserve every supplied input" assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
- zero start
from copy import deepcopy args = (0, 7) before = deepcopy(args) expected = (0, 7) result = old_and_new(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for zero start" assert args == before, "Preserve every supplied input" assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
- negative start
from copy import deepcopy args = (-3, 2) before = deepcopy(args) expected = (-3, -1) result = old_and_new(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for negative start" assert args == before, "Preserve every supplied input" assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
- cross zero
from copy import deepcopy args = (2, -5) before = deepcopy(args) expected = (2, -3) result = old_and_new(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for cross zero" assert args == before, "Preserve every supplied input" assert all(type(part) is int for part in result), "Respect nested types and ownership promises"
Does original track later assignments to value?
No. It holds the earlier integer. There is one addition and a fixed-size result; arithmetic costs still depend on integer size.
Transfer: isolate every row
The input is now nested: append a marker to each independently copied row.
The contract
- rows is a list of lists of strings; marker is a string.
- Return a new outer list and new row lists, each original row followed by marker. Keep row order, repeated values and empty rows.
- Never edit the input outer list or any original row. Empty outer input returns a new empty list.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
- one row
from copy import deepcopy args = ([["tea"]], "!") before = deepcopy(args) expected = [["tea", "!"]] result = marked_rows(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for one row" assert args == before, "Preserve every supplied input" assert result is not args[0] and len({id(row) for row in result}) == len(result) and all(type(row) is list and all(row is not original for original in args[0]) for row in result), "Respect nested types and ownership promises" - empty table
from copy import deepcopy args = ([], "!") before = deepcopy(args) expected = [] result = marked_rows(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty table" assert args == before, "Preserve every supplied input" assert result is not args[0] and len({id(row) for row in result}) == len(result) and all(type(row) is list and all(row is not original for original in args[0]) for row in result), "Respect nested types and ownership promises" - empty row
from copy import deepcopy args = ([[]], "!") before = deepcopy(args) expected = [["!"]] result = marked_rows(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty row" assert args == before, "Preserve every supplied input" assert result is not args[0] and len({id(row) for row in result}) == len(result) and all(type(row) is list and all(row is not original for original in args[0]) for row in result), "Respect nested types and ownership promises" - several rows
from copy import deepcopy args = ([["a"], ["b"]], "x") before = deepcopy(args) expected = [["a", "x"], ["b", "x"]] result = marked_rows(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for several rows" assert args == before, "Preserve every supplied input" assert result is not args[0] and len({id(row) for row in result}) == len(result) and all(type(row) is list and all(row is not original for original in args[0]) for row in result), "Respect nested types and ownership promises" - repeated shared row
from copy import deepcopy args = ([["a"]] * 2, "a") before = deepcopy(args) expected = [["a", "a"], ["a", "a"]] result = marked_rows(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for repeated shared row" assert args == before, "Preserve every supplied input" assert result is not args[0] and len({id(row) for row in result}) == len(result) and all(type(row) is list and all(row is not original for original in args[0]) for row in result), "Respect nested types and ownership promises" - empty marker
from copy import deepcopy args = ([["a", "b"], []], "") before = deepcopy(args) expected = [["a", "b", ""], [""]] result = marked_rows(*args) assert type(result) is type(expected) and result == expected, "Return the exact value and type for empty marker" assert args == before, "Preserve every supplied input" assert result is not args[0] and len({id(row) for row in result}) == len(result) and all(type(row) is list and all(row is not original for original in args[0]) for row in result), "Respect nested types and ownership promises"
What changed from independent_add?
Independence is now needed at two levels. Copying only the outer list fails. Work and output storage grow with the number of rows plus the total number of strings.
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 milestoneObjects outlive a name
Deleting a name removes that binding. It does not erase an object still reachable through another reference.
Understand first
When cleaning up working data, you must distinguish removing a local name from releasing every reference. Otherwise a shared resource can seem to vanish or remain alive mysteriously.
Words you will see
- Reachable
- Still accessible through some reference.
- del
- A statement that can remove a name binding or a selected item.
- Garbage collection
- An implementation's mechanism for reclaiming objects that are no longer needed.
Remove a route, not every route
The sample binds remaining to the same list as data. del data removes the name data. remaining still reaches the list, so appending rice and printing its contents work normally. Reading data after deletion would instead raise NameError.
This is different from data.clear(), which would empty the shared list without removing either name. It is also different from deleting an element with del remaining[0]. The target after del determines what is removed.
Do not time resource cleanup by guesswork
CPython normally uses reference counting plus a collector for unreachable reference cycles. Other Python implementations can reclaim unreachable objects at different times. This program relies only on the list remaining reachable, not on a particular collection schedule.
Use a with statement for timely closing of files and other managed resources rather than waiting for the last name to disappear. Removing a large data binding can help make memory reclaimable, but it does not promise an immediate drop in operating-system memory usage.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
remaining = dataKeep another route to the list.
del dataRemove only the binding named data.
remaining.append("rice")Mutate the still-reachable list.
print(remaining)Observe tea and rice without referring to the deleted name.
Deleting or rebinding one name does not destroy an object that is still referenced elsewhere. CPython uses reference counting plus cyclic garbage collection, but code should not rely on exact collection timing across Python implementations.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
Delete an item instead.
Try: Replace del data with del remaining[0].
Both names still exist, but the eventual displayed list contains only rice.
Observe a removed name honestly.
Try: Add print(data) after del data.
Run shows NameError before the later append executes.
Before you move on
If del first removes one of two aliases, may the second alias still read the object?
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
Yes. Removing one binding leaves the second reference intact. The object remains reachable through that reference.
A shallow copy is one new outer object
A shallow copy creates a new outer container but keeps references to the original elements. Nested mutable elements can therefore remain shared.
Understand first
Copying a table's outer list does not isolate its rows. You need to choose the depth of independence required before allowing edits.
Words you will see
- Shallow copy
- A new container referring to the same elements.
- Nested object
- An object stored inside another container.
- Deep copy
- A recursive copy operation that attempts to copy contained objects too.
Separate the outer list from its rows
rows contains one inner list. rows.copy() creates another outer list, so appending a new row to copied does not add a row to rows. But copied[0] still refers to the original inner list. Appending rice through copied[0] edits that shared row.
The first display therefore shows the changed tea row. The second display also contains the separately appended bread row. The third display is False because the two outer lists are different objects. That False does not say their descendants are all independent.
Copy only as deeply as the contract needs
For a table of lists of immutable strings, [row.copy() for row in rows] makes independent rows as well as an independent outer list. copy.deepcopy is useful for more general nested structures, but custom objects and external resources need deliberate ownership rules.
A shallow copy takes work and extra space proportional to the outer list length. Copying all rows also visits their elements. Deep copying can copy much more than intended; prefer a clearly scoped data transformation when the required shape is known.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
copied = rows.copy()Create a new outer list, still pointing to the same row.
copied[0].append("rice")Edit the row shared by both outer lists.
copied.append(["bread"])Add a row only to the new outer list.
print(rows is copied)Show that the outer objects differ despite the shared first row.
a.copy() creates a new list but keeps references to its elements. Nested mutable objects remain shared. Deep copying may be appropriate, but can be costly and is not a substitute for deciding ownership.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
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.
Copy the rows too.
Try: Use copied = [row.copy() for row in rows].
rows keeps [['tea']] while copied contains the edited row and bread.
Replace rather than edit a row.
Try: Replace copied[0].append("rice") with copied[0] = ["rice"].
rows remains [['tea']]; only copied's first slot changes.
Before you move on
Will copied[0] = ['new'] change rows[0] after a shallow copy?
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 statement replaces a slot in the new outer list. It does not mutate the previously shared inner 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.