Python Mutable and Immutable


Mutable and Immutable Data Types in Python

In Python, data types can be categorized into two groups: mutable and immutable. This distinction is important because it affects how you can modify and work with objects in your programs.

Mutable Data Types

Mutable data types are objects that can be modified after they are created. This means you can change their content without changing their identity (the object in memory). When you modify a mutable object, you are changing the object itself rather than creating a new object.

Common Mutable Data Types:

  1. Lists

    • Lists can have items added, removed, or changed.
    • Example:
      my_list = [1, 2, 3] my_list.append(4) # Adding an element print(my_list) # Output: [1, 2, 3, 4] my_list[0] = 10 # Changing an element print(my_list) # Output: [10, 2, 3, 4] my_list.remove(2) # Removing an element print(my_list) # Output: [10, 3, 4]
  2. Dictionaries

    • Dictionaries allow changes to keys and values.
    • Example:
      my_dict = {'name': 'Alice', 'age': 25} my_dict['age'] = 26 # Modifying a value print(my_dict) # Output: {'name': 'Alice', 'age': 26} my_dict['city'] = 'NYC' # Adding a new key-value pair print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'NYC'}
  3. Sets

    • Sets can have elements added or removed.
    • Example:
      my_set = {1, 2, 3} my_set.add(4) # Adding an element print(my_set) # Output: {1, 2, 3, 4} my_set.remove(2) # Removing an element print(my_set) # Output: {1, 3, 4}

Immutable Data Types

Immutable data types are objects that cannot be modified after they are created. Any operation that seems to modify an immutable object will instead create a new object. This means that the original object remains unchanged.

Common Immutable Data Types:

  1. Strings

    • Strings cannot be changed; any modification creates a new string.
    • Example:
      my_string = "Hello" new_string = my_string.replace("H", "J") # Creating a new string print(my_string) # Output: Hello (original remains unchanged) print(new_string) # Output: Jello
  2. Tuples

    • Tuples are similar to lists but cannot be changed once created.
    • Example:
      my_tuple = (1, 2, 3) # my_tuple[0] = 10 # This will raise a TypeError new_tuple = my_tuple + (4,) # Creating a new tuple print(new_tuple) # Output: (1, 2, 3, 4)
  3. Frozensets

    • Frozensets are immutable versions of sets.
    • Example:
      my_frozenset = frozenset([1, 2, 3]) # my_frozenset.add(4) # This will raise an AttributeError

Summary

  • Mutable Data Types: Can be changed after creation (e.g., lists, dictionaries, sets). Modifying them affects the original object.
  • Immutable Data Types: Cannot be changed after creation (e.g., strings, tuples, frozensets). Modifications create new objects instead.

Understanding the difference between mutable and immutable data types is crucial for writing efficient Python code, as it affects how variables behave in your programs and how memory is managed.