Codele / Advanced programming
Values, references and copies
A name does not always hold the thing itself. For a list it holds a note saying where the list lives. Two names with the same note share one list.
- A reference is a note saying where a thing lives in memory, like an address. Lists, objects and most bigger things are held by reference.
- b = a copies the note, not the thing. Two names for one thing are aliases, so a change through one name shows up through the other.
- A copy is a new thing with its own address. Change the copy and the original stays safe. A shallow copy copies only the outer list: lists inside it are still shared. A deep copy copies everything.
- Numbers and text behave like plain values: b = a for a number really gives b its own number. Lists are shared in Python, JavaScript, Java and C#, and Go slices share their items too. C++ is the odd one out: a vector is copied on assignment, and you ask for an alias with &.
Loading the playable lesson…