Codele / Advanced programming
Mutable and immutable data
A whiteboard can be rubbed out and rewritten. A printed page cannot: you print a new one. Some data is changed in place, and some can only be replaced.
- Immutable data cannot be changed in place; to “change” it you make a new value. Text is immutable in Python, JavaScript, Java, C# and Go: upper() gives back a new text and leaves the old one alone.
- Mutable data can be changed in place, like a list. That is handy, but anyone holding the same reference sees the change.
- The bug to watch for: a function that quietly changes the list you gave it. Safer functions build and return a new list, so the caller’s data stays as it was.
- C++ strings are mutable, and C++ copies a list when you pass it unless you write &. Many languages also offer frozen versions on purpose, such as Python’s tuple, JavaScript’s Object.freeze and Java’s List.of.
Loading the playable lesson…