Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand: "the collection of objects directly referenced by an immutable object cannot change"?

From the Python documentation:

An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)

While the first part of the original quote is understandable, I don't quite get the last sentence. How can I understand the phrase: "directly referenced by an immutable object"?

like image 422
ig-melnyk Avatar asked Jan 28 '26 23:01

ig-melnyk


1 Answers

Probably the best way to explain this will be an example.

>>> a = [1, 2, 3]
>>> b = (a, a)

b is a tuple -- an immutable sequence. However, the objects it contains are lists, which are mutable.

It's possible to modify the mutable objects in the collection:

>>> a.append(4)
>>> b
([1, 2, 3, 4], [1, 2, 3, 4])

However, it isn't possible to change which objects exist in a, because it's immutable. The first and second elements of a will always refer to the same list, and there's no way to change that.