Assignment Operators
Python · Operators
Theory
= binds a name to a value. Augmented assignment operators combine an operation with assignment: total += 50 means total = total + 50, and the same pattern exists for -=, *=, /=, //=, %=, **= and others. For immutable values like numbers and strings, Python computes a new object and re-points the name at it. Python has no ++ or -- operators; write count += 1.
For mutable objects the story changes. On a list, x += [3] modifies the existing list in place (just like x.extend([3])), so any other name pointing at the same list sees the change. x = x + [3] instead builds a brand-new list and rebinds only x. Assignment also supports unpacking: a, b = 1, 2 assigns both at once, a, b = b, a swaps without a temporary variable, and a = b = 0 points both names at the same object.
Why we use it
Updating a running total, counter or accumulator is one of the most common things code does. Augmented assignment keeps it short and readable, and understanding in-place behaviour avoids nasty aliasing bugs with lists.
When to use it
Use += for counters and running totals in loops. When a list is shared between names (or passed into a function) and you do not want the original changed, use new = old + [item] instead of +=.
How it works
- Python meets total += 50
- Look up the current value of total (100)
- Is the object a mutable list? Yes: Extend it in place. No: Compute total + 50 as a new object.
- Bind the name total to the result
- print(total) shows 150
Syntax
= += -= *= /=Example
total = 100
total += 50
print(total)Key points
- x += 1 is shorthand for x = x + 1
- Works with all arithmetic operators: -=, *=, /=, //=, **=
- Python has no ++ or --; use += 1
- On lists, += changes the list in place, affecting every alias
- a, b = b, a swaps two values in one line