r/learnpython • • 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

11 comments sorted by

View all comments

Show parent comment

2

u/Expensive-Bear-1376 Oct 23 '26

If you have a = [5] and do  a[0] += 2, would you want a to still be [5] instead of  [7]?

0

u/Bunslow Oct 23 '26

feh, the perils of mixing pointers and nonpointers i guess. even tho i think a container contains pointers, it doesn't really. it would be really funny tho if that code incremented by 2 the address stored in a[0] lol