-
-
Notifications
You must be signed in to change notification settings - Fork 33.9k
Description
Bug report
Bug description:
Windows 11 Pro 25H2, Python 3.14.0, IDLE
Code:
t = (1, 2,[3, 4])
t[2] += [5] # Throws TypeError
print(t) # Shows that previous operation actually completed successfully
I ran the code in IDLE and got a TypeError:
Traceback (most recent call last):
File "<pyshell#47>", line 1, in
t[2] += [5]
TypeError: 'tuple' object does not support item assignment
I then ran print(t) and the output was: (1, 2, [3, 4, 5])
Why did I get an error even though the list was actually updated?
Question to Copilot: does python support changing a list that is inside of a tuple?
Copilot response:
Yes — in Python, tuples are immutable, but that immutability only applies to the tuple structure itself (the references it holds), not to the mutable objects stored inside it.
So if a tuple contains a list, you can modify the contents of that list, because the list itself is mutable — you’re not changing the tuple’s reference, just the list’s internal data.
Example:
# Tuple containing a list
t = (1, [2, 3, 4], "hello")
# Modify the list inside the tuple
t[1][0] = 99
t[1].append(5)
print(t)
Output:
(1, [99, 3, 4, 5], 'hello')
Key Points:
✅ You can change the contents of a mutable object (like a list or dict) inside a tuple.
❌ You cannot reassign the list itself to a new object without creating a new tuple.
From me again:
The issue seems to be the "+=" operator. The "+" concatenates the lists (= [a] + [b]) and then the "="
reassigns to the original reference in the tuple. This assignment part is the likely step that raises
the error because it is determined to be an assignment only.
Shouldn't the "+=" operator or the tuple class check to see if the same object reference is being used
before throwing the error?
CPython versions tested on:
3.14
Operating systems tested on:
Windows