...

/

Puzzle 27: Explanation

Puzzle 27: Explanation

Let’s find out how augmented arithmetic assignments work in Python.

We'll cover the following...

Try it yourself

Try executing the code below to verify the results:

Press + to interact
def add_n(items, n):
items += range(n)
items = [1]
add_n(items, 3)
print(items)

In Puzzle 16: Call Me Maybe, we talked about rebinding versus mutation. Most of the time, items += range(n) is translated to items = items + range(n), a process which is called rebinding.

In some cases, there is a special optimization for +=. Here’s a more detailed explanation from the Python ...