A += Assignment Puzzler in Python

1 minute read

Published:

In the world of programming, it’s not uncommon to come across some puzzling situations that require careful analysis and attention to detail. This is exactly the case with this post, which involves evaluating the following code. Let’s dive into this puzzle and see what we can learn from it.

What happens next? Choose the best answer:

  1. t becomes (1, 2, [30, 40, 50, 60]).
  2. TypeError is raised with the message ‘tuple’ object does not support item assignment.
  3. Neither.
  4. Both 1 and 2.

Tuples are immutable and cannot be changed. Therefore, if we try to change an element of a tuple, a TypeError should be raised. However, tuples store the reference to their members and a list can be changed without changing its reference. Thus, you can modify a list in the tuple! The answer to the previous question is actually 4, “Both 1 and 2”. Here is the output:

As you can see, we have a TypeError states that “‘tuple’ object does not support item assignment”, and surprisingly, t is also changed.

What happened?

Here is what happens in Python:

  • Python puts the value of s[2] on TOS (Top Of Stack).
  • Perform TOS += b. This succeeds since TOS refers to a mutable object in our example (a list).
  • Assign s[2] = TOS. This fails since s is immutable in our example (a tuple).

We take two lessons from this:

  • Avoid putting mutable items in tuples.
  • Augmented assignment is not an atomic operation—we just saw it throwing an exception after doing part of its job.

Reference

[1] Fluent Python