Hone

Lessons · Python · copy or the same thing?

Assignment does not copy

b = a makes a second name for the same list. To get a separate list, copy it: list(a), a[:] or a.copy().

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Pass a list into a function, change it, and the caller's list changed too. Snapshot a cart before applying a discount and the snapshot changes with the cart. Every one of these is a missing copy.

How to think about it

Ask, before you change a list or dict: who else holds this? If anyone, copy first. For nested data, copy.deepcopy, because a shallow copy shares the inner objects.

Worked example

a = [1, 2]
One list.
b = a
Same list, second name.
b.append(3)
Change through b.
print(a)
[1, 2, 3]: changed through b.
c = list(a)
A real copy.
c.append(4)
Change the copy.
print(a)
[1, 2, 3]: a did not see the 4.

Your turn

Keep a snapshot of the cart before changing it.

before = (cart)

The trap

list(a) copies one level. If a holds lists, the copy holds the same inner lists, and changing one inner list shows in both.

Practise copy or the same thing? on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.