Table of Contents

    Mutable and Immutable Data

    Programming Mastery

    Mutable and Immutable Data

    Learn how mutable and immutable data behave in memory, how they affect program safety, and why understanding them helps avoid unexpected bugs.

    Introduction

    In programming, data can behave in two important ways: it can be mutable or immutable.

    Mutable data can be changed after it is created. Immutable data cannot be changed after it is created.

    Mutable means changeable. Immutable means not changeable after creation.

    This concept is very important in memory management, value and reference types, functional programming, object-oriented programming, and data safety.

    Easy Real-Life Example

    Mutable Data as a Whiteboard

    A whiteboard can be changed. You can write something, erase it, and write something new on the same board.

    Whiteboard:
    Original text: "Math Class"
    Changed text:  "Programming Class"
    
    Same whiteboard, changed content.

    This is similar to mutable data. The same object can be changed.

    Immutable Data as a Printed Certificate

    A printed certificate should not be edited directly. If something needs to change, a new certificate is printed.

    Certificate:
    Original certificate: "Aman scored 80"
    New certificate:      "Aman scored 85"
    
    Original certificate is not changed.
    A new certificate is created.

    This is similar to immutable data. Instead of changing the original object, a new object is created.

    What is Mutable Data?

    Mutable data is data that can be changed after it is created.

    If an object is mutable, we can update its contents without creating a completely new object.

    Key Idea: Mutable data allows in-place modification.

    Mutable Data Example

    /*
    This example shows mutable data behavior.
    A list can be changed after creation.
    */
    
    ENTRY POINT
        DECLARE marks AS LIST = [70, 80, 90]
    
        ADD 95 TO marks
    
        DISPLAY marks
    END ENTRY POINT

    Expected Output

    [70, 80, 90, 95]

    Here, the list marks is modified by adding a new value. The same list changes.

    What is Immutable Data?

    Immutable data is data that cannot be changed after it is created.

    If we want a different value, the program creates a new value or object instead of modifying the original one.

    Key Idea: Immutable data does not change in place. A new value is created when modification is needed.

    Immutable Data Example

    /*
    This example shows immutable data behavior.
    Changing text creates a new text value.
    */
    
    ENTRY POINT
        DECLARE message AS TEXT = "Hello"
    
        SET message = message + " World"
    
        DISPLAY message
    END ENTRY POINT

    Expected Output

    Hello World

    Although it looks like the text was changed, many programming languages create a new text value instead of modifying the original text directly.

    Mutable vs Immutable Data

    Feature Mutable Data Immutable Data
    Meaning Can be changed after creation. Cannot be changed after creation.
    Modification Changes happen in the same object. A new object or value is created.
    Memory Behavior Same object may stay in memory with updated content. Original value stays unchanged; new value may be created.
    Safety Can cause unexpected changes if shared. Safer for shared data because original value does not change.
    Flexibility More flexible for frequent updates. More predictable for fixed data.
    Common Examples Lists, dictionaries, sets, objects. Numbers, booleans, strings, tuples in many languages.

    Common Mutable Data Examples

    Exact rules depend on the programming language, but common mutable data types often include:

    Usually Mutable

    • Lists or dynamic arrays.
    • Dictionaries or maps.
    • Sets.
    • Objects created from classes.
    • Mutable string builders or buffer-like structures.
    • Collections whose contents can be updated.

    Example: Mutable List

    ENTRY POINT
        DECLARE students AS LIST = ["Aman", "Riya"]
    
        ADD "Sohan" TO students
    
        DISPLAY students
    END ENTRY POINT

    Expected Output

    ["Aman", "Riya", "Sohan"]

    The list is changed after creation, so it behaves like mutable data.

    Common Immutable Data Examples

    Exact rules depend on the programming language, but common immutable data types often include:

    Usually Immutable

    • Integers.
    • Decimal or floating-point numbers.
    • Booleans.
    • Characters.
    • Strings in many languages.
    • Tuples or fixed collections in some languages.
    • Frozen or read-only collections in some languages.

    Example: Immutable Number

    ENTRY POINT
        DECLARE x AS INTEGER = 10
    
        SET x = x + 5
    
        DISPLAY x
    END ENTRY POINT

    Expected Output

    15

    Conceptually, the value 10 is not changed into 15. Instead, the variable x is updated to refer to or hold a new value.

    Memory Idea Behind Mutability

    Mutability is closely related to how data behaves in memory.

    Mutable Memory Idea

    list1 → [10, 20, 30]
    
    ADD 40 TO list1
    
    list1 → [10, 20, 30, 40]
    
    Same list object, changed content.

    Immutable Memory Idea

    text → "Hello"
    
    text = text + " World"
    
    Old value: "Hello"
    New value: "Hello World"
    
    The original text value is not modified directly.
    Beginner Tip: Mutable objects change their internal state. Immutable objects are replaced with new values when changes are needed.

    Mutable Data and Shared References

    Mutable data can cause unexpected results when two variables refer to the same object.

    Example: Shared Mutable List

    /*
    Both variables refer to the same list.
    Changing one affects the other.
    */
    
    ENTRY POINT
        DECLARE list1 AS LIST = [1, 2, 3]
        SET list2 = list1
    
        ADD 4 TO list2
    
        DISPLAY list1
        DISPLAY list2
    END ENTRY POINT

    Expected Output

    [1, 2, 3, 4]
    [1, 2, 3, 4]

    Since list1 and list2 refer to the same list, modifying the list through list2 also changes what list1 sees.

    Immutable Data and Safe Copies

    Immutable data is safer to share because it cannot be changed in place.

    Example: Immutable Text

    /*
    Both variables first refer to the same text value.
    Reassigning one does not change the original value.
    */
    
    ENTRY POINT
        DECLARE text1 AS TEXT = "Hello"
        SET text2 = text1
    
        SET text2 = text2 + " World"
    
        DISPLAY text1
        DISPLAY text2
    END ENTRY POINT

    Expected Output

    Hello
    Hello World

    text1 remains unchanged because the original text value is not modified directly.

    Mutable Object Example

    /*
    Object properties can often be changed after creation.
    This is mutable behavior.
    */
    
    CLASS Student
        PROPERTY name
        PROPERTY marks
    END CLASS
    
    ENTRY POINT
        CREATE student AS Student
        SET student.name = "Aman"
        SET student.marks = 80
    
        SET student.marks = 90
    
        DISPLAY student.name
        DISPLAY student.marks
    END ENTRY POINT

    Expected Output

    Aman
    90

    The student object is changed after creation because its marks property is updated.

    Immutable Object Example

    Some objects are designed so that their values cannot be changed after creation.

    /*
    Immutable-style student record.
    Instead of changing existing data,
    create a new record with updated value.
    */
    
    RECORD StudentRecord
        FIELD name
        FIELD marks
    END RECORD
    
    ENTRY POINT
        CREATE oldRecord AS StudentRecord("Aman", 80)
    
        CREATE newRecord AS StudentRecord("Aman", 90)
    
        DISPLAY oldRecord
        DISPLAY newRecord
    END ENTRY POINT

    Expected Output

    StudentRecord("Aman", 80)
    StudentRecord("Aman", 90)

    The old record remains unchanged. A new record is created for the updated marks.

    Reassignment vs Mutation

    Beginners often confuse reassignment with mutation.

    Concept Meaning Example Idea
    Reassignment The variable is made to hold or refer to a different value. x = 10, then x = 20
    Mutation The object itself is changed. Add item to existing list.

    Reassignment Example

    x = 10
    x = 20

    Here, the variable x is reassigned.

    Mutation Example

    numbers = [1, 2, 3]
    ADD 4 TO numbers

    Here, the list object is mutated.

    Function Argument Example with Mutable Data

    Mutable data can be changed inside a function if the function receives a reference to the same object.

    /*
    The function modifies the original list.
    */
    
    FUNCTION addBonusMark(marks)
        ADD 5 TO marks
    END FUNCTION
    
    ENTRY POINT
        DECLARE studentMarks AS LIST = [70, 80, 90]
    
        CALL addBonusMark(studentMarks)
    
        DISPLAY studentMarks
    END ENTRY POINT

    Expected Output

    [70, 80, 90, 5]

    The original list is changed because the function modifies the same mutable object.

    Function Argument Example with Immutable Data

    Immutable data usually does not change outside the function when modified inside the function.

    /*
    The function changes its local value,
    but the original value remains unchanged.
    */
    
    FUNCTION increase(number)
        SET number = number + 1
        DISPLAY "Inside function: " + number
    END FUNCTION
    
    ENTRY POINT
        DECLARE count AS INTEGER = 10
    
        CALL increase(count)
    
        DISPLAY "Outside function: " + count
    END ENTRY POINT

    Expected Output

    Inside function: 11
    Outside function: 10

    The original count remains unchanged because the function works with its own local value.

    Why Immutable Data is Useful

    Immutable data is useful because it makes programs more predictable.

    Benefits of Immutable Data

    • Reduces unexpected changes.
    • Makes data safer to share.
    • Makes debugging easier.
    • Helps write pure functions.
    • Supports functional programming style.
    • Can improve reliability in concurrent programs.
    • Helps preserve historical data versions.
    • Makes reasoning about code easier.

    Why Mutable Data is Useful

    Mutable data is useful when we need frequent updates and flexible changes.

    Benefits of Mutable Data

    • Useful for collections that grow or shrink.
    • Efficient for repeated updates.
    • Good for dynamic data such as shopping carts.
    • Useful for forms, dashboards, games, and simulations.
    • Allows modifying object properties directly.
    • Can avoid creating too many new objects in some situations.

    Real-World Example: Shopping Cart

    A shopping cart is usually mutable because users can add, remove, or update items.

    cart = []
    
    ADD "Keyboard" TO cart
    ADD "Mouse" TO cart
    REMOVE "Mouse" FROM cart
    
    DISPLAY cart

    Expected Output

    ["Keyboard"]

    The cart changes over time, so mutable data is suitable here.

    Real-World Example: Transaction Record

    A financial transaction record should often be treated as immutable because changing old transaction data can be dangerous.

    transaction1 = {
        "id": 101,
        "amount": 500,
        "status": "Completed"
    }
    
    If correction is needed:
    Create transaction2 or adjustment record
    Do not silently modify transaction1

    Immutable-style data helps preserve trust, history, and auditability.

    Mutable and Immutable Data in Functional Programming

    Functional programming often prefers immutable data.

    Instead of changing the original data, functional programming encourages creating new transformed data.

    Functional Immutable Style

    /*
    Original list remains unchanged.
    A new list is created.
    */
    
    ENTRY POINT
        DECLARE oldMarks AS LIST = [70, 80, 90]
    
        DECLARE updatedMarks AS LIST = MAP each mark IN oldMarks:
            RETURN mark + 5
    
        DISPLAY oldMarks
        DISPLAY updatedMarks
    END ENTRY POINT

    Expected Output

    [70, 80, 90]
    [75, 85, 95]

    This approach avoids changing the original data.

    Copying Mutable Data

    When working with mutable data, copying must be handled carefully.

    list1 = [1, 2, 3]
    list2 = list1
    
    ADD 4 TO list2
    
    DISPLAY list1

    Output

    [1, 2, 3, 4]

    This happens because list2 may refer to the same list as list1.

    Safer Copy Idea

    list1 = [1, 2, 3]
    list2 = COPY OF list1
    
    ADD 4 TO list2
    
    DISPLAY list1
    DISPLAY list2

    Output

    [1, 2, 3]
    [1, 2, 3, 4]

    Creating a real copy prevents accidental modification of the original list.

    Shallow Copy and Deep Copy

    With mutable nested data, copying can be more complex.

    Copy Type Meaning Risk
    Reference Copy Copies only the reference. Both variables share the same object.
    Shallow Copy Copies the outer object. Nested objects may still be shared.
    Deep Copy Copies outer and inner objects. Safer but may use more memory.

    Students should understand this concept before working with nested lists, dictionaries, objects, and complex data structures.

    Mutable Data, Immutable Data, and Value/Reference Types

    Mutable and immutable data are related to value and reference types, but they are not exactly the same concept.

    Concept Main Question Example
    Value Type vs Reference Type Does the variable store the value directly or a reference? Number value vs object reference.
    Mutable vs Immutable Can the object/value be changed after creation? List can change; string may not.
    Important: A reference type can be mutable or immutable depending on the language and data structure.

    Performance Considerations

    Mutable and immutable data can affect performance differently.

    General Performance Ideas

    • Mutable data can be efficient when many updates are needed.
    • Immutable data can create new objects when values change.
    • Too many immutable updates may create extra temporary objects.
    • Mutable data can reduce copying but may increase bug risk.
    • Immutable data can improve predictability and safety.
    • The best choice depends on language, program design, and problem requirement.

    Common Bugs Caused by Mutable Data

    Mutable data is powerful, but it can create hidden side effects.

    FUNCTION addStudent(students)
        ADD "New Student" TO students
    END FUNCTION
    
    ENTRY POINT
        classList = ["Aman", "Riya"]
    
        CALL addStudent(classList)
    
        DISPLAY classList
    END ENTRY POINT

    Output

    ["Aman", "Riya", "New Student"]

    If the caller did not expect the original list to change, this becomes a bug.

    How to Avoid Mutable Data Bugs

    Safe Practices

    • Create copies before modifying shared mutable data.
    • Use immutable data when values should not change.
    • Avoid modifying function arguments unless clearly intended.
    • Use clear function names such as addItemInPlace if mutation is intentional.
    • Use read-only or frozen structures when available.
    • Prefer pure functions for calculations.
    • Document when a function changes input data.

    Advantages of Mutable Data

    • Good for frequently changing data.
    • Useful for building lists, maps, sets, and dynamic collections.
    • Can be memory-efficient when updating large structures in place.
    • Simple to use for interactive applications.
    • Useful for game state, UI state, and temporary working data.

    Advantages of Immutable Data

    • Safer to share between different parts of a program.
    • Helps prevent accidental changes.
    • Easier to reason about during debugging.
    • Useful in functional programming.
    • Good for constants, configuration, records, and historical data.
    • Can help avoid side effects.

    Limitations of Mutable Data

    • Shared references can cause unexpected changes.
    • Harder to debug when many parts modify the same object.
    • May cause side effects in functions.
    • Requires careful copying when original data must be preserved.
    • Can create concurrency problems if shared between multiple tasks.

    Limitations of Immutable Data

    • May create new objects for every change.
    • Can be less efficient for very frequent updates.
    • May require different thinking for beginners.
    • Can require special techniques for large data transformations.
    • Not always ideal for highly dynamic state.

    When to Use Mutable Data

    Use Mutable Data When

    • The data needs frequent updates.
    • You are building a collection step by step.
    • You need to add, remove, or update items often.
    • The object represents changing state.
    • Performance requires avoiding repeated object creation.
    • The mutation is controlled and clear.

    When to Use Immutable Data

    Use Immutable Data When

    • The value should not change after creation.
    • You want safer shared data.
    • You are writing pure functions.
    • You want to avoid unexpected side effects.
    • You are storing constants or fixed records.
    • You need easier debugging and predictable behavior.

    Common Beginner Mistakes

    Mistakes

    • Thinking assignment always creates a new object.
    • Changing a list through one variable and being surprised another variable also changes.
    • Confusing reassignment with mutation.
    • Assuming strings behave like mutable lists.
    • Modifying function arguments accidentally.
    • Forgetting to copy mutable data before changing it.
    • Thinking immutable data means variables cannot be reassigned.
    • Assuming mutability rules are identical in every language.

    Better Habits

    • Ask whether the object itself is changing.
    • Use copies when original mutable data must remain unchanged.
    • Use immutable data for fixed values.
    • Use clear function names when mutation happens.
    • Learn mutability rules of the language you are using.
    • Prefer pure functions when possible.
    • Be careful with shared references.
    • Test mutability behavior with small examples.

    Best Practices

    Recommended Practices

    • Use mutable data only when changes are required.
    • Use immutable data when safety and predictability are important.
    • Do not modify input data unexpectedly inside functions.
    • Create new values instead of changing old values when using functional style.
    • Use defensive copying when receiving mutable data from outside.
    • Avoid sharing mutable objects across many parts of a program.
    • Use read-only views or immutable collections when available.
    • Keep mutation localized and controlled.
    • Document functions that mutate their inputs.
    • Choose clarity and correctness before micro-optimization.

    Prerequisites Before Learning This Topic

    Students should understand the following topics before learning mutable and immutable data deeply:

    Required Knowledge

    • Variables and constants.
    • Data types.
    • Assignment operator.
    • Value type and reference type.
    • Stack and heap concept.
    • Functions and parameters.
    • Arrays and lists.
    • Strings.
    • Objects and classes.
    • Basic memory concept.

    Trace Table Example: Mutable Data

    list1 = [1, 2]
    list2 = list1
    ADD 3 TO list2
    Step Action list1 list2
    1 Create list1 [1, 2] Not created
    2 list2 refers to same list [1, 2] [1, 2]
    3 Add 3 using list2 [1, 2, 3] [1, 2, 3]

    Trace Table Example: Immutable Data

    text1 = "Hi"
    text2 = text1
    text2 = text2 + " There"
    Step Action text1 text2
    1 Create text1 "Hi" Not created
    2 Assign text1 to text2 "Hi" "Hi"
    3 Reassign text2 "Hi" "Hi There"

    Practice Activity: Identify Mutable or Immutable

    Identify whether the behavior is mutable or immutable.

    1. A list allows adding a new element after creation.
    2. A string does not allow changing one character directly.
    3. A dictionary allows updating the value of a key.
    4. A number variable is reassigned from 10 to 20.
    5. A tuple-like fixed collection cannot be changed after creation.
    6. A student object allows updating the marks property.

    Sample Answers

    1. Mutable
    2. Immutable
    3. Mutable
    4. Immutable-style value reassignment
    5. Immutable
    6. Mutable

    Mini Quiz

    1

    What is mutable data?

    Mutable data is data that can be changed after it is created.

    2

    What is immutable data?

    Immutable data is data that cannot be changed after it is created.

    3

    Give one example of mutable data.

    A list is commonly mutable because items can be added, removed, or updated.

    4

    Give one example of immutable data.

    A string is immutable in many languages because its characters cannot be changed directly after creation.

    5

    Why is immutable data useful?

    Immutable data is useful because it reduces unexpected changes and makes programs easier to reason about.

    Interview Questions on Mutable and Immutable Data

    1

    Explain mutable data with an example.

    Mutable data can be changed after creation. For example, a list can be updated by adding or removing elements.

    2

    Explain immutable data with an example.

    Immutable data cannot be changed after creation. For example, a string in many languages cannot be modified directly; a new string is created instead.

    3

    What is the difference between mutation and reassignment?

    Mutation changes the object itself, while reassignment makes a variable hold or refer to a different value.

    4

    Why can mutable data cause bugs?

    Mutable data can cause bugs when multiple variables or functions share the same object and one part changes it unexpectedly.

    5

    Why does functional programming prefer immutable data?

    Functional programming prefers immutable data because it helps avoid side effects and makes functions more predictable.

    Quick Summary

    Concept Meaning
    Mutable Data Data that can be changed after creation.
    Immutable Data Data that cannot be changed after creation.
    Mutation Changing the object itself.
    Reassignment Making a variable hold or refer to another value.
    Mutable Example List, dictionary, set, mutable object.
    Immutable Example Number, boolean, string, tuple-like fixed data.
    Main Risk of Mutable Data Unexpected changes through shared references.
    Main Benefit of Immutable Data Predictability and safety.

    Final Takeaway

    Mutable data can be changed after creation, while immutable data cannot be changed after creation. Mutable data is useful for dynamic updates, but it can cause unexpected side effects when shared. Immutable data is safer and more predictable, especially in functional programming and shared-data situations. In the Memory and Resource Management Basics module, students should understand mutability clearly because it affects assignment, copying, function arguments, object behavior, memory usage, and program reliability.