top | item 21862399

(no title)

Luyt | 6 years ago

Of course you can. The first element of that tuple is a list, which is mutable, and can be sorted in-place.

discuss

order

FartyMcFarter|6 years ago

So the question is if += and sort are both "in-place", why does one throw and the other doesn't? Clearly "in-place" is not the full explanation here.

I think the real explanation is that with += there are two steps:

1- The existing list gets modified. This is fine since lists are mutable.

2- The tuple's reference to the list gets updated (even though this update is unnecessary since the list object's identity is the same).

The exception occurs at step 2, but this step is otherwise a no-op. Whether mutating a reference to the same value it already had is an actual mutation is an interesting semantics debate.

Luyt|6 years ago

Tuples are immutable, but that doesn't mean they can't contain references to mutable objects.

When you want to use a tuple as a key in a dictionary, Python checks if all members of the tuple are immutable. If one or more of them aren't, you'll get an 'unhashable type' error.