Mutable Objects in Python

Carson West

Default Parameters

Mutable Objects in Python

Mutable objects in Python are objects whose internal state can be changed after they are created. This means you can modify their contents without creating a new object. In contrast, immutable objects cannot be changed after creation; any operation that appears to modify them actually creates a new object.

Key characteristics of mutable objects:

Examples of Mutable Objects:

my_list = 1, 2, 3
my_list.append(4)  # Modifies the original list
print(my_list)  # Output: 1, 2, 3, 4
my_dict = {'a': 1, 'b': 2}
my_dict['c']] = 3  # Modifies the original dictionary
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}
my_set = {1, 2, 3}
my_set.add(4) # Modifies the original set
print(my_set) # Output: {1, 2, 3, 4}

Important Considerations:

list1 = 1, 2, 3
list2 = list1  # list2 is an alias for list1
list1.append(4)
print(list2)  # Output: 1, 2, 3, 4  (list2 is also modified)

Immutable Objects in Python (Note: This will be a seperate note)

Shallow vs Deep Copying (Note: This will be a seperate note)