This is more of a curiosity
Say I have the following code
>>> my_immutable = (1, 2)
>>> my_immutable[0] += 1
TypeError: 'tuple' object does not support item assignment
This is expected, because unlike C, Python does not modify the underlying int, but rather creates a new one (observed in the code below)
>>> x = 1
>>> id(x)
33156200
>>> x += 1
>>> id(x)
33156176
If I want to modify the underlying integer in the tuple, I can hackly do something like
>>> hacked_immutable = ([1], [2])
>>> hacked_immutable[0][0] += 1
>>> hacked_immutable
([2], [2])
My question is: is there a nicer way of doing it (ideally performant and ideally already in the standard library)? Some wrapper class around int maybe?
Edit: I did not have a specific software that had to adhere to this. It was more of a thought exercise of why are things like this. I think the three questions I had were:
-
Why are ints immutable? (still not sure)
-
Is there a way to force them to be mutable? (wim's answer)
-
Is there a nice way to force them to be mutable (like Integer vs int in Java) - I think the answer is NO?
Thanks a lot for the discussion!