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

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

  • Β Duck Typing

    Python, Polymorphism allows us to use a single interface (like a function or a method) for objects of different types. Duck Typing is a specific style of polymorphism common in dynamically-typed languages like Python. What is Duck Typing? πŸ¦† The name comes from the saying: “If it walks like a duck and it quacks like…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Else Block in Exception Handling in Python

    Else Block in Exception Handling in Python The else block in Python exception handling executes only if the try block completes successfully without any exceptions. It’s placed after all except blocks and before the finally block. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else: # Code that runs only if no exception…

  • What are Variables

    A program is essentially a set of instructions that tells a computer what to do. Just like a recipe guides a chef, a program guides a computer to perform specific tasksβ€”whether it’s calculating numbers, playing a song, displaying a website, or running a game. Programs are written in programming languages like Python, Java, or C++,…

Leave a Reply

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