r/learnpython • u/Bunslow • Oct 23 '26
In-place updates to objects count as tuple assignment?
Test case:
s = {1, 2, 3, 4}
grid = tuple(s.copy() for i in range(2))
print(f"{grid[1]=}")
one = grid[1]
one &= {2, 3}
print(f"{grid[1]=}")
grid[1] &= {2}
The output is as so:
grid[1]={1, 2, 3, 4}
grid[1]={2, 3}
Traceback (most recent call last):
File "/home/bill/bin/fivefold/test.py", line 7, in <module>
grid[1] &= {2}
~~~~^^^
TypeError: 'tuple' object does not support item assignment
Is it me or is this very surprising, a seeming violation of self-consistent behavior of Python? Simply renaming the reference to the object changes how I may or may not mutate the object. Clearly I'm not modifying the tuple, just deferencing the pointer to the contained object. version 3.11.2
0
Upvotes
View all comments
Show parent comment
2
u/Expensive-Bear-1376 Oct 23 '26
If you have
a = [5]and doa[0] += 2, would you wantato still be[5]instead of[7]?