Which Of The Following Data Types Is Immutable In Python

5 min read

Understanding data mutability is a cornerstone of writing efficient, bug-free Python code. When developers ask which of the following data types is immutable in python, they are usually looking for a clear distinction between objects that can change after creation and those that cannot. This concept dictates how data is stored in memory, how it behaves when passed to functions, and whether it can be used as a dictionary key or set element.

In Python, every value is an object, and every object has an identity (memory address), a type, and a value. Mutability refers to the ability of an object to change its internal state or value after it has been created. Still, an immutable object cannot be modified once instantiated; any operation that appears to change it actually creates a brand-new object in memory. Conversely, a mutable object allows in-place modifications.

The Core Immutable Data Types

Python provides several built-in immutable types. Knowing these by heart is essential for certification exams, technical interviews, and daily development.

1. Numeric Types: int, float, complex

Numbers are the most fundamental immutable objects. When you perform arithmetic on a variable holding a number, Python creates a new numeric object and rebinds the variable name to it Most people skip this — try not to..

x = 10
print(id(x))  # Memory address A
x += 5        # x is now 15
print(id(x))  # Memory address B (different from A)

The original integer 10 remains untouched in memory (subject to garbage collection), and x simply points to the new integer 15.

2. Strings (str)

Textual data in Python is immutable. You cannot change a character inside an existing string.

name = "Python"
# name[0] = "J"  # TypeError: 'str' object does not support item assignment
name = "J" + name[1:]  # Creates a completely new string "Jython"

Methods like .upper(), .replace(), or .strip() always return new string objects, leaving the original intact It's one of those things that adds up. Simple as that..

3. Tuples (tuple)

Tuples are ordered sequences, similar to lists, but they are immutable. Once defined, you cannot add, remove, or change elements That's the part that actually makes a difference..

coordinates = (10, 20, 30)
# coordinates[0] = 15 # TypeError

That said, a critical nuance exists: a tuple containing mutable objects (like lists) can have its internal mutable objects changed.

data = (1, 2, [3, 4])
data[2].append(5)  # This works! The list inside the tuple mutates.
# data is now (1, 2, [3, 4, 5])

The tuple itself (the sequence of references) hasn't changed, but the object it refers to has.

4. Frozen Sets (frozenset)

A frozenset is the immutable counterpart to the standard set. It supports set operations like union and intersection but cannot be modified after creation. Because it is immutable and hashable, it can be used as a dictionary key or an element of another set—something a regular set cannot do.

5. Bytes (bytes) and Byte Arrays (bytearray distinction)

The bytes type represents an immutable sequence of bytes (integers 0-255). It behaves much like a string but for binary data. Note that bytearray is the mutable version of this type.

6. Booleans (bool)

True and False are singletons in Python. They are instances of bool (a subclass of int) and are strictly immutable.

The Core Mutable Data Types (For Contrast)

To fully grasp immutability, you must recognize the mutable built-ins:

  • Lists (list): append(), pop(), sort(), slice assignment.
  • Byte Arrays (bytearray): Mutable sequence of bytes.
  • Sets (set): add(), remove(), update(). Worth adding: g. Think about it: * Dictionaries (dict): Adding/removing key-value pairs, updating values. Here's the thing — * Custom Classes: By default, user-defined class instances are mutable unless specifically designed otherwise (e. , using __slots__ or dataclasses with frozen=True).

Why Immutability Matters: Practical Implications

The distinction isn't academic; it has profound effects on how Python programs run Not complicated — just consistent..

1. Dictionary Keys and Set Elements

Only hashable objects can be dictionary keys or set members. An object is hashable if its hash value never changes during its lifetime. Immutability is a prerequisite for hashability (with minor exceptions for custom objects) Easy to understand, harder to ignore..

  • Valid keys: Strings, numbers, tuples (containing only immutable items), frozensets.
  • Invalid keys: Lists, dictionaries, sets, bytearrays.
# Valid
valid_dict = { (1, 2): "tuple key", "name": "string key" }

# Invalid
# invalid_dict = { [1, 2]: "list key" } # TypeError: unhashable type: 'list'

2. Function Argument Passing (Call by Object Reference)

Python uses a mechanism called "Call by Object Reference."

  • Immutable arguments: The function cannot change the original object in the caller's scope. Reassigning the parameter inside the function only points the local variable to a new object.
  • Mutable arguments: The function can modify the object's contents (e.g., appending to a list), affecting the caller's object. Reassigning the parameter variable itself still only affects the local reference.
def modify_immutable(s):
    s += " world"  # Creates new local string object

def modify_mutable(lst):
    lst.append(99) # Modifies the actual list object in place

text = "Hello"
modify_immutable(text)
print(text) # "Hello" (Unchanged)

numbers = [1, 2, 3]
modify_mutable(numbers)
print(numbers) # [1, 2, 3, 99] (Changed!)

3. Performance and Memory Optimization

  • Interning: Python automatically interns small integers (typically -5 to 256) and some strings. Because they are immutable, multiple variables pointing to the value 10 actually point to the exact same memory address. This saves memory.
  • Optimization: Since immutable objects never change, the interpreter can optimize memory layout and caching strategies aggressively.
  • Copies: Copying an immutable object (e.g., tuple(my_tuple)) is often a no-op or returns the same object because there is no risk of future mutation. Copying a mutable object requires creating a distinct copy (shallow or deep) to prevent side effects.

4. Thread Safety

Immutable objects are inherently thread-safe. If multiple threads read an immutable object, no race conditions can occur because no thread can write to it. This simplifies concurrent programming significantly.

Common "Gotchas" and Edge Cases

The "Mutable Default Argument" Trap

This is the most infamous Python pitfall related to mutability. Default arguments are evaluated once—at function definition time, not call time.

def add_item(item, shopping_list=[]):
    shopping_list.append(item)
    return shopping_list

print(add_item("Apple")) # ['Apple']
print(add_item("Banana")) # ['Apple', 'Banana'] <- Oops! On the flip side, shared state. Plus, ```
**The Fix**: Use `None` as the default and create the mutable object inside the function. ```python
def add_item(item, shopping_list=None):
    if shopping_list is None:
        shopping_list = []
    shopping_list.

### Tuple Immutability vs. Content Mutability
As shown earlier, a tuple is immutable *structurally* (you cannot replace its elements), but not
New In

Recently Launched

Worth Exploring Next

Readers Also Enjoyed

Thank you for reading about Which Of The Following Data Types Is Immutable In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home