What are immutable objects in Python?
What are immutable objects in Python?
Immutable objects in Python are objects whose state cannot be modified after they are created. This means that the contents of these objects cannot be altered. When you attempt to change an immutable object, what actually happens is that a new object is created with the new value, and the variable referencing the original object is updated to point to this new object. The original object remains unchanged.
Examples of immutable objects in Python include:
Integers: Once an integer is created, its value cannot be changed. Any operation that seems to modify the value of an integer actually creates a new integer object, and the reference is updated to this new object[1][2].
Floats: Similar to integers, float values are also immutable. Any change results in a new float object being created[3].
Strings: Strings in Python are immutable. If you concatenate, slice, or otherwise modify a string, a new string object is created, and the reference to the old string is replaced with a reference to the new string[1][2][6].
Tuples: Tuples are immutable sequences in Python. Once a tuple is created, you cannot add, remove, or change its elements. However, if a tuple contains mutable objects, such as lists, those contained objects can still be modified[1][2][6].
The immutability of these objects has several implications:
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào