Mutable vs Immutable

What Does Mutable vs Immutable in Python?

In Python:
- Mutable: Objects that can be changed after creation.
- Immutable: Objects that cannot be changed after creation.

Why is this Important?

Understanding mutability is essential because:
- It impacts memory management.
- It determines how objects behave when passed to functions.
- It helps avoid bugs related to unintended modification.

Examples of Mutable and Immutable Types.

Mutable Types
Mutable objects can be modified in place without creating a new project.
Examples include:
- lists
- dictionaries
- sets
- bytearry

Immutable Tyes
Immutable objects cannot be modified in place. Any modification results in a new object being created.
Examples include:
- integers
- floats
- strings
- tuples
- booleans
- frozenset
- bytes

Key Differences Between Mutable and Immutable


FeatureMutableImmutable
DefinitionCan be changed after creation.Cannot be changed after creation.
ExamplesLists, Dictionaries, SetsIntegers, Strings, Tuples    
PerformanceSlower for some operations (due to in-place modification).Faster because objects cannot change.
Memory UsageMay reuse memory.Creates a new object when modified.



Examples of Mutable and Immutable Types

1. Mutable Example: List
Lists can be modified in place.

    fruits = ["apple", "banana", "cherry"]
    fruits[1] = "blueberry"
    print(fruits)  # Output: ['apple', 'blueberry', 'cherry']

2. Immutable Example: String
Strings cannot be modified. Any operation that changes a string creates a new object.

    text = "hello"
    text = text.upper()
    print(text)  # Output: 'HELLO'

Checking Object Identity

The id() function helps verify whether an object has been modified or a new object is created.

Mutable Object
    numbers = [1, 2, 3]
    print(id(numbers))  # Example: 140283515703040
    numbers.append(4)
    print(id(numbers))  # Same ID: 140283515703040 (modified in place)


Immutable Object
    num = 10
    print(id(num))  # Example: 140283515702320
    num += 1
    print(id(num))  # Different ID: 140283515702352 (new object created)


Passing Mutable and Immutable Objects to Functions

Mutable Example

Modifications inside a function affect the original object.

    def add_item(my_list):
        my_list.append(4)

    numbers = [1, 2, 3]
    add_item(numbers)
    print(numbers)  # Output: [1, 2, 3, 4]
Immutable Example

Modifications inside a function do not affect the original object.

    def add_one(num):
        num += 1
        return num
    
    x = 10
    y = add_one(x)
    print(x)  # Output: 10
    print(y)  # Output: 11


Use Cases for Mutable and Immutable Objects.

When to Use Mutable Objects
  • When you need to modify a collection frequently.
  • Examples:
    • Maintaining a dynamic list of users.
    • Updating a dictionary of configurations.
When to Use Immutable Objects
  • When data should remain constant to prevent accidental changes.
  • Examples:
    • Storing keys in a dictionary (immutable types like strings or tuples).
    • Using constants (e.g., PI = 3.14).

Practice Problems

1. Create a function that appends an item to a list passed as an argument. 

2. Test how mutable and immutable objects behave differently. Write a program to demonstrate how strings are immutable by attempting to change a character.

3. Implement a dictionary where keys must be tuples and demonstrate the immutability of tuple keys.

Patrick

Life is too short. Let's hang out!

Post a Comment

Previous Post Next Post