Mutable vs. Immutable Objects in Python πŸ”„πŸ”’

Mutable vs. Immutable Objects in Python πŸ”„πŸ”’

In Python, mutability determines whether an object’s value can be changed after creation. This is crucial for understanding how variables behave. πŸ€”


Immutable Objects πŸ”’

  • Cannot be modified once created. Any “change” creates a new object. πŸ†•
  • Types: int, float, str, bool, tuple, frozenset, bytes, NoneType.

Example 1: Strings (Immutable) πŸ’¬

Python

s = "hello"
print(id(s))  # Original memory address: e.g., 140245678945600

s += " world"  # "Modification" creates a NEW string
print(id(s))  # New address: e.g., 140245678946880 (different!)

Example 2: Tuples (Immutable) πŸ“¦

Python

t = (1, 2, [3, 4])
print(t)       # (1, 2, [3, 4])
# t[0] = 99    # TypeError: tuple does not support item assignment
# But note: The inner list is mutable!
t[2].append(5)  # The tuple's structure hasn't changed (still holds same list)
print(t)        # (1, 2, [3, 4, 5])

Mutable Objects πŸ“

  • Can be modified in-place without creating a new object. ✍️
  • Types: list, dict, set, bytearray.

Example 1: Lists (Mutable) πŸ“‹

Python

colors = ["red", "green"]
print(id(colors))  # Original address: e.g., 140245678947392

colors.append("blue")  # Modified IN-PLACE
print(colors)          # ["red", "green", "blue"]
print(id(colors))      # Same address: 140245678947392

Example 2: Dictionaries (Mutable) πŸ“š

Python

person = {"name": "Alice", "age": 30}
print(id(person))  # Original address: e.g., 140245678946112

person["age"] = 31  # Change value in-place
person["city"] = "Paris"  # Add new key-value pair
print(person)       # {'name': 'Alice', 'age': 31, 'city': 'Paris'}
print(id(person))   # Same address: 140245678946112

Key Implications: πŸ€”

Equality vs. Identity βš–οΈπŸ†”

  • == checks if values are equal.
  • is checks if they refer to the exact same object in memory.

Python

a = [1, 2]  # Mutable
b = [1, 2]  # Different object
print(a == b)  # True (same value)
print(a is b)  # False (different memory)

x = "abc"    # Immutable
y = "abc"    # Python may reuse same object (interning)
print(x is y) # Often True (due to interning for small, immutable objects)

Function Arguments πŸ”„

  • Mutable objects passed to functions can be changed globally. 🌍
  • Immutable objects behave like “copies” inside functions. πŸ“„

Python

def update_list(lst):
    lst.append(99)  # Affects original list

def try_update_string(s):
    s += "!"        # Creates new string (no effect outside)

my_list = [1, 2]
my_str = "Hello"

update_list(my_list)
try_update_string(my_str)

print(my_list)  # [1, 2, 99] (changed)
print(my_str)   # "Hello" (unchanged)

Summary Table: πŸ“Š

PropertyMutableImmutable
Can modify?Yes (in-place)No (new object on change)
Memory addressSame after modificationChanges after “modification”
Exampleslist, dict, setint, str, tuple
Use CaseDynamic collectionsConstants, safe data

Export to Sheets

Similar Posts

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. πŸŒ€ Polymorphism…

  • Finally Block in Exception Handling in Python

    Finally Block in Exception Handling in Python The finally block in Python exception handling executes regardless of whether an exception occurred or not. It’s always executed, making it perfect for cleanup operations like closing files, database connections, or releasing resources. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else:…

  • circle,Rational Number

    1. What is a Rational Number? A rational number is any number that can be expressed as a fraction where both the numerator and the denominator are integers (whole numbers), and the denominator is not zero. The key idea is ratio. The word “rational” comes from the word “ratio.” General Form:a / b Examples: Non-Examples: 2. Formulas for Addition and Subtraction…

  • Mathematical Functions

    1. abs() Syntax: abs(x)Description: Returns the absolute value (non-negative value) of a number. Examples: python # 1. Basic negative numbers print(abs(-10)) # 10 # 2. Positive numbers remain unchanged print(abs(5.5)) # 5.5 # 3. Floating point negative numbers print(abs(-3.14)) # 3.14 # 4. Zero remains zero print(abs(0)) # 0 # 5. Complex numbers (returns magnitude) print(abs(3 +…

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

Leave a Reply

Your email address will not be published. Required fields are marked *