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

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • TheΒ Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”β€”the regex engine looks ahead in the string to see if the pattern inside…

  • Top Programming Languages and Tools Developed Using Python

    Python itself is not typically used to develop other programming languages, as it is a high-level language designed for general-purpose programming. However, Python has been used to create domain-specific languages (DSLs), tools for language development, and educational languages. Here are some examples: 1. Hy 2. Coconut Description: A functional programming language that compiles to Python. It adds…

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • Data hiding

    Data hiding in Python OOP is the concept of restricting access to the internal data of an object from outside the class. πŸ” It’s a way to prevent direct modification of data and protect the object’s integrity. This is typically achieved by using a naming convention that makes attributes “private” or “protected.” πŸ”’ How Data…

Leave a Reply

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