Hone

Lessons · Python · two names, one list

Two names for one list

b = a does not copy a list. Both names point at the same one.

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

It is the bug that makes people distrust their own code. You change one thing and something unrelated changes too, and nothing in the code looks wrong.

How to think about it

Ask: do I want another NAME for this, or another COPY of it? Assignment gives a name. a[:] or list(a) gives a shallow copy.

Worked example

a = [1, 2]
One list exists.
b = a
Still one list. Two names pointing at it.
b.append(3)
Changes the one list they share.
print(a)
Prints [1, 2, 3]. a was never touched by name, but it is the same object.
c = a[:]
NOW there are two lists. Changing c leaves a alone.

Your turn

Make a copy that can change independently.

a = [1, 2]
b = a[]
b.append(3)
print(a)

The trap

a[:] copies the outer list only. If it holds other lists, those are still shared, which is what copy.deepcopy exists for.

Practise two names, one list on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.