Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python variables: names refer to objects, assignment does not copy

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

A Python variable is a name bound to an object; assigning that object to another name does not create an independent copy.

Download Python source kit

Operation contract

The dispatch batch is a list. A second name points to that same list, so appending through the second name changes the batch. A shallow copy gives a separate outer list; adding a new entry there does not extend the original. The fixture uses immutable strings so outer-copy independence is easy to inspect. Identity and equality answer different questions.

Failure and ownership boundary

Rebinding a name differs from mutating its object. Copying a nested list still shares its inner objects, and passing a list into a function does not revoke the caller’s access to it. State who owns mutation before calling the copy an immutable snapshot. Python lists: slicing copies the outer sequence, not nested objects and Java pass-by-value: references and mutation describe comparable aliasing problems with different language rules.

Working program

python
dispatch_batch = ["receipt-41"]
shared_batch = dispatch_batch
shared_batch.append("receipt-42")
copied_batch = dispatch_batch.copy()
copied_batch.append("receipt-43")
print(dispatch_batch)
print(copied_batch)
print(shared_batch is dispatch_batch)

Output

Output
['receipt-41', 'receipt-42']
['receipt-41', 'receipt-42', 'receipt-43']
True

Costs and limits

Binding another name has bounded reference work. Copying n list entries takes O(n) time and O(n) outer storage; it does not recursively duplicate referenced objects.

Common Mistakes

  • Assignment does not copy mutable state.
  • A shallow copy does not isolate nested objects.

Connected lessons

Python lists: slicing copies the outer sequence, not nested objects, Python tuples: immutable containers can still contain mutable state, Java pass-by-value: references and mutation.

Apply this boundary

Python shallow and deep copies: preserve aliases deliberately, Python linked-list reversal: validate cycles before changing links.

Follow the related contract

Python truth values: distinguish missing data from valid zero, Python type conversion: parsing success is not field validity.

python
python-variables
Storage details