Mutation and Copying

Mutation means changing an object in place.

Output:

[8, 6, 9]

The list object changed. The name scores still refers to the same list.

Two Names, One List

This surprises many beginners:

Output:

[1, 2, 3]

a and b refer to the same list. Mutating through b changes the object that a also sees.

Shared list

Both names refer to the same list object.

Runs locally with Python in your browser.

Ready to run.

Make a Shallow Copy

Use .copy() when you want a separate list:

Output:

[1, 2]
[1, 2, 3]

Now a and b refer to different lists.

This is a shallow copy: the outer list is new, but mutable objects nested inside it would still be shared. The flat lists in this chapter do not need a deeper copying strategy.

Reassignment Is Different

This is not mutation:

The second line makes the name scores refer to a new list. Mutation changes the existing list. Reassignment changes what the name points to.

Assignment Does Not Copy a List

Assuming b = a copies a list. It does not. It copies the reference: both names point to the same object.

Exercise: Shared mutation

What does this print?

Answer it first, then check.

HintTrack the object, not only the names

b = a gives the same list a second name. Then append() mutates that shared list.

SolutionBoth names see the mutation

a and b refer to the same list object. Appending 2 through b changes that object, so printing a displays [1, 2].

Know When Two Names Share One Object

When a collection changes unexpectedly, ask whether two names refer to the same object. Many bugs begin there.