Sobes.tech
Junior — Middle

What happens if you apply the += operator to a list inside a tuple?

sobes.tech AI

Answer from AI

If you have a tuple containing a list, and you apply the += operator to that list inside the tuple, the list itself will be modified (mutated), not the tuple. The tuple as an object remains unchanged, but the list contained within it will change.

Example:

t = ([1, 2], 3)
t[0] += [3, 4]
print(t)  # Outputs: ([1, 2, 3, 4], 3)

Here, the += operator extends the list inside the tuple. It's important to understand that += for a list is an extension operation (mutation), not creating a new object. The tuple itself does not change because the reference to the list remains the same, but the contents of the list are modified.

What happens if you apply the += operator to a list… - sobes.tech