Mutable and Immutable types

 Mutable and Immutable types


In Python, the concepts of mutable and immutable types are important because they define whether the value of an object can be changed after it is created.

Mutable Types:

A mutable object is one whose state or content can be changed after it is created. In other words, you can modify, add, or remove elements of a mutable object without creating a new object.

Examples of Mutable Types:

  • list: You can add, remove, or modify elements in a list.

    my_list = [1, 2, 3]
    my_list[0] = 100  # Modify element
    my_list.append(4)  # Add element
    print(my_list)  # Output: [100, 2, 3, 4]
    
  • dict: You can change the value of a key, add new key-value pairs, or delete a key-value pair.

    my_dict = {"name": "Alice", "age": 25}
    my_dict["age"] = 26  # Modify value
    my_dict["city"] = "New York"  # Add new key-value pair
    print(my_dict)  # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
    
  • set: You can add or remove elements from a set.

    my_set = {1, 2, 3}
    my_set.add(4)  # Add element
    my_set.remove(2)  # Remove element
    print(my_set)  # Output: {1, 3, 4}
    

Immutable Types:

An immutable object is one whose state or content cannot be changed after it is created. Once an immutable object is created, you cannot modify it in place. Any operation that seems to modify an immutable object actually creates a new object.

Examples of Immutable Types:

  • int: The value of an integer cannot be changed once it is created.

    x = 10
    x = x + 5  # This creates a new integer object, x now points to 15
    print(x)  # Output: 15
    
  • float: Similarly, the value of a float cannot be changed in place.

    y = 3.14
    y = y * 2  # This creates a new float object, y now points to 6.28
    print(y)  # Output: 6.28
    
  • tuple: Once a tuple is created, you cannot modify its elements.

    my_tuple = (1, 2, 3)
    # my_tuple[0] = 100  # This will raise an error, as tuples are immutable
    
  • str: Strings in Python are immutable. Any operation that seems to change a string creates a new string.

    my_string = "hello"
    my_string = my_string.upper()  # Creates a new string
    print(my_string)  # Output: "HELLO"
    
  • frozenset: A frozenset is an immutable version of a set. You cannot add or remove elements after it is created.

    my_frozenset = frozenset([1, 2, 3])
    # my_frozenset.add(4)  # This will raise an error
    

Key Differences:

  • Mutability refers to whether the object can be changed after it is created. Mutable objects can be altered, whereas immutable objects cannot.
  • Efficiency: Immutable types are typically more memory-efficient, especially in terms of hashing (e.g., dictionaries and sets use immutable types for keys).
  • Behavior in functions: When you pass a mutable object to a function, changes made to that object inside the function will affect the original object outside the function. However, when you pass an immutable object, any changes inside the function will not affect the original object.

Summary:

  • Mutable types (e.g., list, dict, set) can be modified after creation.
  • Immutable types (e.g., int, str, tuple, frozen set) cannot be modified once created. Any modification creates a new object.