mutable vs immutable objects #859
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.
Uh oh!
There was an error while loading. Please reload this page.
-
What are mutable vs immutable objects?
Beta Was this translation helpful? Give feedback.
All reactions