Understanding Mutable and Immutable Objects in Python

In Python, everything is treated as an object, which includes both data and the relations between data. Every object in Python has three main attributes:

  1. Identity: The unique address of the object in memory, which does not change throughout the object’s lifetime.
  2. Type: The data type of the object (like integer, list, or string) which dictates what values the object can hold. This is also unchangeable.
  3. Value: The actual data or information contained in the object, which can be either mutable (changeable) or immutable (unchangeable).

Mutable Objects

Mutable objects are those that can change their value after they are created. Common mutable data types in Python include:

  • Lists
  • Dictionaries
  • Sets
  • Bytearrays

When you modify a mutable object, Python does not create a new object in memory; instead, it modifies the existing object. Here are some examples to demonstrate this behavior:

Example 1: Modifying a List

Create a list of animals

animals = ['cat', 'dog', 'goat', 'cow']
print('Original list:', animals)
print('Original ID:', id(animals))  # Prints the memory ID of the list

Append a new animal to the list

animals.append('buffalo')
print('List after appending:', animals) # Shows the list after adding 'buffalo'
print('ID after appending:', id(animals)) # The ID remains the same, showing mutability

Remove an animal from the list

animals.remove('dog')
print('List after removing:', animals) # Shows the list after removing 'dog'
print('ID after removing:', id(animals)) # The ID still remains the same

Example 2: Changing List Elements

Creating a list of numbers

numbers = [20, 40, 60, 80, 100]
print('Original list:', numbers)
print('Original ID:', id(numbers)) # Prints the original ID of the list

Change the third element

numbers[2] = 50 # Change the value at the third index from 60 to 50
print('Updated list:', numbers) # Print the updated list
print('Updated ID:', id(numbers)) # The ID remains the same, showing that the list is mutable

Immutable Objects

Immutable objects cannot change their value once they are created. Examples of immutable data types include:

  • Integers
  • Floats
  • Strings
  • Tuples

Any attempt to change an immutable object will result in the creation of a new object in memory.

Example: Modifying a String (Immutable Object)

Creating a string

greeting = "Hello"
print('Original string:', greeting)
print('Original ID:', id(greeting)) # Print the original ID of the string

Attempt to modify the string

greeting += ", World!"
print('Modified string:', greeting) # Shows the modified string
print('New ID:', id(greeting)) # The ID changes, showing that strings are immutable

Share on :

Social Share

Recent Post

© 2024 All rights reserved by Go1digital.com