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
3
u/Temporary_Pie2733 Oct 23 '26 edited Oct 23 '26
Assignments to a name are fundamental operations. Assignments to indexed names are essentially syntactic sugar for a call to
__setitem__, which must exist. The version withoneis equivalent toone = one.__iand__({2,3}). The one withgrid[1]isgrid.__setitem__(1, …), notgrid[1].__iand__(…).