PythonPython Operators and ExpressionsPython assignment operators
What are assignment operators?
Question 44 of 88 · Updated
On this page
- 1. Assignment syntax at a glance
- 2. Ordinary assignment
- 3. Arithmetic augmented assignment
- 4. Bitwise augmented assignment
- 5. Is x += y equivalent to x = x + y?
- 6. Mutation versus rebinding
- 7. Why complex assignment targets are evaluated only once
- 8. Custom in-place operations and fallback
- 9. Augmented assignment is not transactional
- 10. Assignment expressions and the walrus operator
- 11. Practical example: update a frequency or quantity mapping
- 12. Assignment and variable scope
- 13. Common assignment errors
- 14. When should you use augmented assignment?
- Interview-ready answer
- Official references
Assignment operators and assignment syntax in Python associate values with targets. Ordinary assignment uses =; augmented assignment combines an operation with assignment, using forms such as +=, -= and *=. Python also provides the assignment expression :=, which binds a name and returns a value inside permitted expressions.
Although these forms are commonly grouped as assignment operators, ordinary and augmented assignments are statements in Python's grammar. They are not expressions that independently return a result.
1. Assignment syntax at a glance#
| Syntax | Operation |
|---|---|
x = y | Assign the evaluated value of y to target x |
x += y | Addition or supported in-place addition |
x -= y | Subtraction |
x *= y | Multiplication |
x /= y | True division |
x //= y | Floor division |
x %= y | Modulo |
x **= y | Exponentiation |
x @= y | Matrix multiplication for compatible types |
x &= y | Bitwise AND or supported overloaded operation |
| `x \ | = y` |
x ^= y | Bitwise XOR or supported overloaded operation |
x <<= y | Left shift |
x >>= y | Right shift |
(x := y) | Assignment expression; bind a name and produce its value |
The exact semantics of augmented operations depend on the operand types. The same syntax can mutate an existing object, produce a different object or raise an exception.
2. Ordinary assignment#
Ordinary assignment evaluates the right-hand expression and assigns its result to the target. A name assignment creates or changes a binding; it does not automatically copy the object.
For instance, x = 10 binds x to an integer. Later assigning x = 20 changes the binding. Python also permits attribute and subscription targets, such as account.balance = 20 or values[0] = 20, subject to their respective assignment contracts.
The earlier variables and multiple-assignment lessons cover name binding, unpacking, chained assignment and shared references in depth. This lesson focuses on the distinct semantics of augmented assignment and practical operator selection.
3. Arithmetic augmented assignment#
PYTHONx = 10 x += 3 x *= 2 x -= 6 print(x)
Output:
20The intermediate values are 13, 26 and 20. Augmented assignment is particularly useful when a calculation updates an existing accumulator.
Other arithmetic assignment forms retain the underlying operators' meanings.
PYTHONx = 17 x //= 5 print(x) x %= 2 print(x) x **= 3 print(x) x /= 2 print(x)
Output:
3
1
1
0.5In this example, true division changes the resulting value from an integer to a float. An augmented assignment does not guarantee preservation of the original type.
Floor division, modulo and exponentiation follow the arithmetic rules discussed in the preceding arithmetic-operators lesson. Matrix multiplication assignment requires types that support matrix multiplication; ordinary scalar integers do not support it.
4. Bitwise augmented assignment#
PYTHONx = 6 x &= 3 print(x) x |= 4 print(x) x ^= 1 print(x) x <<= 1 print(x) x >>= 2 print(x)
Output:
2
6
7
14
3The operations update the integer value according to the corresponding bitwise rules. In this example, the OR operation sets a bit, XOR toggles a bit, and the shifts change bit positions.
There is no logical augmented assignment syntax such as and= or or=. Logical operations have short-circuit evaluation semantics that are different from ordinary bitwise operations.
For sets and other types, some of these symbols represent different operations according to the type's contract.
5. Is x += y equivalent to x = x + y?#
For a simple integer variable, the two statements often produce the same numerical result. In general, however, they are not interchangeable.
Augmented assignment:
- Evaluates its assignment target and obtains its current value.
- Evaluates the right-hand expression.
- Attempts the appropriate in-place operation if supported.
- If necessary, uses the corresponding ordinary binary-operation rules.
- Assigns the resulting value back to the target.
Exceptions from target access, operand evaluation, the operation or assignment can interrupt this sequence. The flowchart describes the successful dispatch path and its ordinary fallback, not exception recovery.
For example, addition assignment can use __iadd__. If the method is missing or returns NotImplemented, Python falls back to the ordinary addition dispatch rules, which may include __add__ and __radd__.
An in-place method is not required to return the original object. Its result is assigned back to the target. It can also return a new object or raise an exception.
6. Mutation versus rebinding#
PYTHONa = [1] b = a a += [2] print(a, b, a is b) x = (1,) y = x x += (2,) print(x, y, x is y)
Output:
[1, 2] [1, 2] True
(1, 2) (1,) FalseFor ordinary lists, += extends the existing list. Both a and b observe the modification because they refer to that list. For tuples, the operation produces a tuple result and rebinds x; y continues to refer to the original tuple.
The choice matters when functions or components share references. Augmented assignment can introduce visible side effects, while rebinding a simple local name may leave other references unchanged.
Do not use augmented assignment merely because an object is mutable. Decide whether the operation is intended to modify existing shared state or produce an independent result.
7. Why complex assignment targets are evaluated only once#
A significant difference between ordinary assignment and augmented assignment becomes apparent with indexed or attribute targets.
PYTHONdata = [10, 20] def index(): print("index") return 0 data[index()] += 5 print(data)
Output:
index
[15, 20]The index expression is evaluated once during the augmented assignment. Contrast this with an explicit ordinary-assignment rewrite:
PYTHONdata = [10, 20] def index(): print("index") return 0 data[index()] = data[index()] + 5 print(data)
Output:
index
index
[15, 20]The ordinary assignment evaluates the right-hand expression before assigning to the target, which requires evaluating index again. In this example the two index calls return the same value. If they had side effects or produced different results, the behavior could differ more substantially.
Augmented assignment evaluates its target before the right-hand expression, in contrast to ordinary assignment's right-hand-first rule. This is important when target expressions or right-hand expressions modify related state.
8. Custom in-place operations and fallback#
PYTHONclass Value: def __init__(self, n): self.n = n def __iadd__(self, other): return NotImplemented def __add__(self, other): return Value(self.n + other) a = Value(2) b = a a += 3 print(a.n, b.n, a is b)
Output:
5 2 FalseThe in-place addition implementation declines the operation using NotImplemented. The ordinary addition method produces a new Value instance, and a is rebound to that result.
The example assumes that the other operand is a compatible integer. A production numeric class should define its supported operand contract and return NotImplemented for unsupported operand combinations when appropriate.
NotImplemented is a dispatch sentinel, not the same thing as None or the NotImplementedError exception. Returning None from an in-place method does not request ordinary-operation fallback: it can result in the assignment target being set to None.
9. Augmented assignment is not transactional#
An augmented operation can mutate an object before the final assignment fails.
PYTHONt = ([1],) try: t[0] += [2] except TypeError: print(t)
Output:
([1, 2],)The tuple itself does not permit element assignment. However, its element is a mutable list. Python retrieves the list, performs in-place addition, and then attempts to assign the resulting list back to the tuple position. The final assignment raises TypeError, but the list has already been modified.
This is not a violation of tuple immutability: the tuple still contains the same list reference. The referenced list has changed.
Similarly, augmented assignment is not a synchronization primitive. Shared-state updates may require locks, transactions or other concurrency controls, depending on the application.
10. Assignment expressions and the walrus operator#
Python 3.8 introduced assignment expressions using :=. An assignment expression binds a name and returns the assigned value where the grammar permits it.
PYTHONif (size := len("book")) > 3: print(size)
Output:
4The expression evaluates len("book"), binds size to 4 and uses that value in the comparison.
An assignment expression differs from ordinary assignment, which does not return a value as an expression. The target of := must be a name, not an arbitrary attribute or indexed target. Parentheses and placement restrictions depend on the surrounding expression.
Use assignment expressions when they eliminate a genuinely repeated computation while keeping the condition readable. A separate assignment is often simpler for beginners and for conditions involving several intermediate values.
11. Practical example: update a frequency or quantity mapping#
PYTHONtotals = {} for name, qty in [("pen", 2), ("book", 1), ("pen", 3)]: totals[name] = totals.get(name, 0) totals[name] += qty print(totals)
Output:
{'pen': 5, 'book': 1}Each key receives an initial zero if it is missing, followed by an augmented addition. This is a common accumulation pattern for quantities and counts.
A single ordinary assignment using totals[name] = totals.get(name, 0) + qty would be simpler for this particular dictionary. Alternatively, collections.defaultdict(int) is useful when missing keys should automatically initialize to zero. The example uses two explicit steps to demonstrate subscription assignment and augmented assignment separately.
For n records and k distinct keys, ordinary dictionary accumulation typically takes O(n) work and O(k) additional storage under conventional hash-table assumptions and bounded-size arithmetic. Actual costs also depend on key hashing, equality, collisions and integer sizes.
12. Assignment and variable scope#
PYTHONx = 1 def f(): x = 2 x += 3 return x print(f(), x)
Output:
5 1The local x is updated inside f, while the module-level x remains unchanged. An augmented assignment to a name inside a function is still an assignment for scope classification.
A function that attempts x += 1 without establishing a local binding or declaring the intended global or nonlocal name can raise UnboundLocalError. The previous variable-scope lesson explains the rules in more detail.
13. Common assignment errors#
Each of the following cases was independently tested.
| Operation | Expected exception | Explanation |
|---|---|---|
x = 1; x /= 0 | ZeroDivisionError | True division by zero |
x = 1; x += "2" | TypeError | Unsupported numeric/string addition |
x = 1; x @= 2 | TypeError | Built-in scalar integers do not implement matrix multiplication |
if x = 1: with a pass body | SyntaxError | Ordinary assignment is invalid as a condition expression |
A function executing x += 1 before a local binding exists | UnboundLocalError | Local name read before initialization |
The tuple/list example in section 9 demonstrates a separate caught TypeError and shows why an exception does not necessarily undo an earlier mutation.
Prefer correcting the underlying operand types, target contract or scope rather than masking the problem with an overly broad exception handler.
14. When should you use augmented assignment?#
Use augmented assignment when an existing value is being updated by a clear operation, such as incrementing a counter, extending a list intentionally or updating a bit mask.
Use ordinary assignment when creating a new value, explicitly replacing a binding, or when a more verbose expression communicates the transformation more clearly.
For mutable shared objects, document whether an operation changes the object in place. For indexed and attribute targets, understand the target evaluation and assignment order. For shared concurrent state, use appropriate synchronization rather than assuming compact syntax implies atomicity.
Interview-ready answer#
Python uses = for ordinary assignment and augmented forms such as +=, -=, *=, /=, //=, %=, **= and bitwise assignment operators to combine an operation with assignment. Augmented assignment evaluates the target once, attempts the corresponding in-place operation and can fall back to ordinary binary-operation semantics, then assigns the result. Consequently, x += y is not universally equivalent to x = x + y: mutable objects may be modified in place, and complex targets may be evaluated differently. Python also supports the := assignment expression in permitted contexts. Ordinary assignment and augmented assignment are statements, not equality tests.
Official references#
- Python Language Reference — Assignment statements
- Python Language Reference — Augmented assignment statements
- Python Language Reference — Emulating numeric types
- Python Language Reference — Assignment expressions
- PEP 203 — Augmented Assignments
- PEP 572 — Assignment Expressions
- Python Language Reference — Execution model
Verification note: Eleven independent runnable examples matched their documented outputs on CPython 3.13.5, including the caught partial-mutation error. Five additional expected-exception tests passed. The fenced Mermaid diagram was manually reviewed for operation order and fallback semantics; the Mermaid CLI was not installed locally, so parser-level validation and website rendering were not performed. Official references are supplied under the authorized offline research exception. Live documentation and the Supabase changelog could not be checked.
References
- 1.Python Language Reference — Assignment statementsdocs.python.org
- 2.Python Language Reference — Emulating numeric typesdocs.python.org
- 3.Python Language Reference — Assignment expressionsdocs.python.org
- 4.PEP 203 — Augmented Assignmentspeps.python.org
- 5.PEP 572 — Assignment Expressionspeps.python.org
- 6.Python Language Reference — Execution modeldocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design