mutable vs immutable objects #859
-
|
What are mutable vs immutable objects? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
Mutable and immutable objects basically differ in whether their value can change after creation. Mutable objectsThese can be modified in place — meaning you don’t create a new object when you change them. Examples in Python:
a = [1, 2, 3]
a.append(4)
print(a) # [1, 2, 3, 4]Here, the same object Immutable objectsThese cannot be changed once created. Any operation that seems like a modification actually creates a new object. Examples:
a = 10
a = a + 5
print(a) # 15This doesn’t modify the original Think of a checkout system. Once the final price is calculated, you don’t want anything accidentally changing it later. If it’s mutable, some part of the code might tweak it without you noticing. So you keep it immutable, once set, it can’t be changed. |
Beta Was this translation helpful? Give feedback.
-
In programming, mutable and immutable objects describe whether an object’s state can change after it’s created. Mutable objectsA mutable object can be modified in place—its internal data/state changes. Immutable objectsAn immutable object cannot be modified after creation. Any “change” produces a new object instead. Why it matters |
Beta Was this translation helpful? Give feedback.
In programming, mutable and immutable objects describe whether an object’s state can change after it’s created.
Mutable objects
A mutable object can be modified in place—its internal data/state changes.
Example (Python): list
You can append/remove/update elements without creating a new list.
Example (JavaScript): Map, Set, plain objects ({})
You can add/remove entries or properties
Immutable objects
An immutable object cannot be modified after creation. Any “change” produces a new object instead.
Example (Python): tuple, str, int, frozenset
Example (JavaScript): strings ("abc") are immutable; operations like concatenation create a new string.
Why i…