My Day✳All blog articles ↗

Distinguish a list alias from a separate flat copy

Check whether names refer to the same list before expecting changes to stay independent.

Assigning a Python list to another name does not itself copy its data. Both names can refer to one mutable object. The copy method makes a shallow copy. This trace uses flat integer lists only; it does not establish full independence for nested objects.

Shared list: lengths a=3, b=3; fresh copy case: a=2, b=3.
Shared list: lengths a=3, b=3; fresh copy case: a=2, b=3.

What to do

  1. Start the first case with a fresh list and mark the object each name refers to.
  2. After append, record both names’ contents without treating two names as two objects.
  3. Restart independently for the copy case and compare its two resulting lists.

Example

Fictional independent cases: a=[1,2]; b=a; b.append(3) gives a=[1,2,3], b=[1,2,3]. Start fresh: a=[1,2]; b=a.copy(); b.append(3) gives a=[1,2], b=[1,2,3]. Final lengths are 3,3 and 2,3. The second case does not continue the first.

My Day · Windows

In My Day, manually save the check and your next action; verify the source yourself.

Buy My Day for Windows ↗