An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:

you are viewing a single comment's thread
view the rest of the comments
[–] 3 points 1 year ago* (1 child)

Except if __iadd__ doesn't exist on the type, then __add__ is called. The variable is always reassigned. Quick example:

x = (0, [1, 2])
try:
    x[1] += [3]  # calls list.__iadd__, then reassigns x[1]
except TypeError as e:
    print(e)

x += (4,)  # calls tuple.__add__, then reassigns x

print(x)

What is printed?

  • source
  • parent
  • hideshow 1 child comment