Intermediate Topic 27 of 54 Programming Fundamentals
Mutability
Whether an object can be changed after creation.
How it works
Mutable objects can be changed in place, while immutable ones cannot, so any change creates a new object. Immutability makes sharing safe, enables caching and hashing, and removes whole classes of concurrency bugs because no thread can alter the value. Mutability is efficient for large, frequently changing data because it avoids copying.
Step-by-step walkthrough
- a = [1, 2] creates a mutable list.
- b = a makes a second name for the same list.
- b.append(3) changes the object itself.
- So a shows [1, 2, 3] as well.
- Immutable values such as tuples and strings create a new object on every change.
Where it is used
Strings and tuples are often immutable, and lists and dictionaries are mutable. Immutable values are used for dictionary keys, configuration, message passing between threads and functional-style state management.
Common pitfall
Aliasing is the major danger: two names pointing to one mutable object means a change through one is seen by the other. Shallow copies share nested mutable objects. Default mutable arguments and shared class-level lists cause surprising state leaks. Copy deliberately or use immutable types.
Where it fits in the course
Mutability is topic 27 of 54 in Programming Fundamentals, rated Intermediate. It follows Pass by Value vs Reference. The next topic is Error Handling.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Mutability?
Where do people use Mutability?
What is the most common mistake with Mutability?
What should I learn before this topic?
How can I practice it?
Is Mutability hard to learn?
How long does it take to learn Mutability?
Which topics are related to Mutability?
What should I study after Mutability?
Related topics
- Pass by Value vs Reference (Programming Fundamentals)
- Error Handling (Programming Fundamentals)
- Call Stack (Programming Fundamentals)
- Exceptions (Programming Fundamentals)