A mutable object can be changed after it's created, and an immutable object can't. When you "change" an immutable object, you're really creating a new object with the new value, and the original stays exactly the same.
For example, lists are mutable in Python:
And tuples are immutable:
Strings can be mutable or immutable depending on the language.
Strings are immutable in Python:
But in some other languages, like Ruby, strings are mutable:
Mutable objects are nice because you can make changes in-place, without allocating a new object. But be careful—whenever you make an in-place change to an object, all references to that object will now reflect the change.
Mutable vs. Immutable
| Mutable | Immutable | |
|---|---|---|
| Can it change after it's created? | Yes, in place | No—"changing" it makes a new object |
| Shared references | A change through one reference shows up through all of them | Safe to share, since nobody can change it |
| Cost of an update | Cheap: just change it | Has to copy, so building one up piece by piece (like repeatedly adding to a string) can take O(n²) time overall |
| Using it across threads | Needs locks or other synchronization if any thread might change it | Safe to share between threads without locks |
| As a dictionary key | Risky: if the key changes after you insert it, you might not be able to find it again | Works great |
| Examples in Python 3.6 | Lists, dictionaries, sets, and bytearrays | Numbers, strings, tuples, frozensets, and bytes |
Neither one is better across the board. Use mutable objects when you need to make lots of updates efficiently, and immutable ones when you want values that can be shared freely without anyone changing them out from under you.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake