Learn the difference between mutable and immutable data types with clear examples. Discover Python's mutable (list, dict, set) and immutable (int, str, tuple) types and why they matter in programming.
An immutable object cannot be changed after it is created. Any operation that modifies it will create a new object instead of altering the original.
A mutable object can be modified after creation without creating a new object.
Feature | Immutable | Mutable |
---|---|---|
Modification | Cannot be changed after creation | Can be changed after creation |
Memory | New object created on modification | Same object modified in-place |
Thread Safety | Safe for concurrent access | May require synchronization |
Examples | int , str , tuple (Python) |
list , dict , set (Python) |
lst = [1, 2, 3]
lst.append(4) # Original list is modified
d = {"a": 1}
d["b"] = 2 # Original dict is modified
s = {1, 2, 3}
s.add(4) # Original set is modified
ba = bytearray(b'hello')
ba[0] = 72 # Modified in-place
Integers are numbers without any fractional part. In Python, integers are immutable, meaning their value cannot be changed once they are created.
Example:
x = 10
print(x) # Output: 10
x = 20 # This creates a new integer object and binds x to it
print(x) # Output: 20
In this example, when x
is reassigned from 10 to 20, a new integer object is created, and x
is updated to reference the new object.
Strings are sequences of characters. In Python, strings are also immutable. Any operation that modifies a string will create a new string rather than altering the existing one.
Example:
s = "hello"
print(s) # Output: hello
s = s + " world" # This creates a new string object
print(s) # Output: hello world
Here, concatenating " world"
to s
does not change the original string "hello"
. Instead, a new string "hello world"
is created and assigned to s
.
Tuples are ordered collections of elements. Like integers and strings, tuples are immutable. Once a tuple is created, you cannot change its contents.
Example:
t = (1, 2, 3)
print(t) # Output: (1, 2, 3)
# Attempting to modify the tuple will raise an error
try:
t[0] = 4
except TypeError as e:
print(e) # Output: 'tuple' object does not support item assignment
# You can create a new tuple
t = (4, 5, 6)
print(t) # Output: (4, 5, 6)
In this example, trying to change the first element of t
results in a TypeError
because tuples are immutable. To change the contents, a new tuple must be created.
These examples illustrate that integers, strings, and tuples in Python are immutable, meaning their values cannot be changed after they are created.