Programming foundations

Stage 1 · Lesson 7 of 9

References, mutability and copying

Your first language

In Python a variable holds a reference to an object. Think of it as a label stuck on a box, not a box with its own copy. After b = a where a is a list, both names point to the same list, so b.append(4) changes a too.

Sharing like this is called . Lists, dictionaries and sets are : they can change in place. Ints, floats, strings and are , so any "change" makes a new object.

That is why a that appends to a list parameter changes the caller's list, while one that adds 1 to an int parameter does not. Copy a list with list(a), a.copy() or a[:]. Remember that this is a shallow copy: for a list of lists, the inner lists are still shared. The next stage shows what this looks like in memory.

A question to check yourself, an AI practice session and 1 cheat sheet entry come when you add the roadmap to your account. Add it

Resources for this stage

Start with· follow one of these

Practise

  • Small exercises in your language track, with free feedback from a human mentor

Keep handy

  • The official tour: read the matching chapter after the course covers a topic

  • Quick syntax lookups and an online compiler for testing a snippet on a shared computer

Mark this stage as not done?