Clarification on Immutability please

Chris Angelico rosuav at gmail.com
Tue Jan 21 14:53:56 EST 2020


On Wed, Jan 22, 2020 at 5:56 AM Michael Torrie <torriem at gmail.com> wrote:
>
> On 1/21/20 11:38 AM, Chris Angelico wrote:
> > Are you sure that it does? I can't reproduce this. When you slice the
> > first two from a tuple, you create a new tuple, and until the
> > assignment happens, both the new one and the original coexist, which
> > means they MUST have unique IDs.
>
> And furthermore this has nothing to do with immutability. Slicing
> returns a new object whether one is slicing a tuple, list, or a string,
> the latter two are mutable objects.

True, but the distinction between immutable objects and non-mutating
operations is a subtle one. Consider:

# Non-mutating operation - new ID every time
>>> obj = [1, 2]
>>> id(obj)
140403205854912
>>> obj = obj + [3, 4]
>>> id(obj)
140403205953728

# Immutable object - all operations are non-mutating
>>> obj = (1, 2)
>>> id(obj)
140403205954304
>>> obj += (3, 4)
>>> id(obj)
140403240175712

# Mutable object - direct mutation is possible
>>> obj = [1, 2]
>>> id(obj)
140403205953728
>>> obj += [3, 4]
>>> id(obj)
140403205953728

So, technically you're right, and it's the operation and not the
object that defines this. But the distinction is very subtle and not
truly significant here, as it's just a matter of descriptive wording.

ChrisA


More information about the Python-list mailing list