Python Assignment Operators
Learn how Python assignment and augmented assignment operators create, update, and reassign variable values with clear examples.
Python assignment operators bind a value to a variable or update a value that a variable refers to. A variable is an identifier that gives a value a usable name. Python evaluates the expression on the right-hand side first, then assigns the resulting value to the target on the left-hand side.
For background, review Python variables, numeric variables, and arithmetic operators.
Basic assignment with =
The basic assignment operator is =. It stores a value or the result of an expression in a variable. This is often called initialization when it gives a variable its first value.
score = 10
print(score)
price = 4
quantity = 3
total = price * quantity
print(total) # 12
In total = price * quantity, Python evaluates price * quantity first. It then binds the result, 12, to total.
Assignment is not equality comparison
= assigns a value. == is the equality operator; it compares two values and produces True or False.
count = 5
print(count == 5) # True
Writing count == 6 does not update count. It only tests a condition.
Augmented assignment
An augmented assignment combines an arithmetic or other supported operation with reassignment. Its general form is:
variable operator= expression
For example, points += 3 uses the current value of points, adds 3, and assigns the result back to points. Augmented assignment is especially useful for counters, running totals, balances, and other accumulators.
For ordinary numeric values, x operator= y is broadly equivalent to x = x operator y. Python evaluates the right-hand expression using the variable's current value, performs the operation, and then updates the target.
Python assignment operators reference
Addition assignment: +=
+= adds the right-hand value to the current value and stores the result. It is commonly used to increment a counter or maintain a running total.
counter = 5
counter += 3
print(counter) # 8
total = 0
for number in [2, 4, 6]:
total += number
print(total) # 12
Addition assignment also works with compatible sequences. For example, strings can be extended with another string, and lists can be extended with another iterable such as a list.
message = "Hello"
message += " Python"
print(message) # Hello Python
items = ["pen", "book"]
items += ["lamp"]
print(items) # ['pen', 'book', 'lamp']
Lists are mutable objects, so list += commonly modifies the existing list in place. This matters when another variable refers to that same list.
first = [1, 2]
second = first
first += [3]
print(second) # [1, 2, 3]
If an independent list is needed, make a copy before updating it, for example with second = first.copy().
Subtraction assignment: -=
-= subtracts the right-hand operand from the current value.
balance = 5
balance -= 3
print(balance) # 2
lives = 3
lives -= 1
print(lives) # 2
Multiplication assignment: *=
*= multiplies the current value by the right-hand operand.
quantity = 5
quantity *= 3
print(quantity) # 15
For compatible sequences, multiplication assignment can repeat a sequence.
pattern = ["red"]
pattern *= 3
print(pattern) # ['red', 'red', 'red']
True-division assignment: /=
/= uses true division. With ordinary numeric operands, the stored result is typically a float, even when the division is exact.
value = 5
value /= 3
print(value) # 1.6666666666666667
print(type(value)) # <class 'float'>
whole = 8
whole /= 2
print(whole) # 4.0
Use //= when floor-division behavior is intended instead of true division.
Modulo assignment: %=
%= updates a variable to the remainder after division. The modulo symbol does not mean percentage notation in Python.
value = 5
value %= 3
print(value) # 2
Modulo is useful for cyclic positions. If there are 4 slots numbered 0 through 3, applying %= 4 wraps a position back into that range.
position = 3
position += 1
position %= 4
print(position) # 0
Exponentiation assignment: **=
**= raises the current value to a power and stores the result.
number = 5
number **= 3
print(number) # 125
Floor-division assignment: //=
//= performs floor division. It stores the quotient rounded down toward negative infinity, not simply a quotient with its decimal portion removed.
items = 5
items //= 3
print(items) # 1
negative = -5
negative //= 3
print(negative) # -2
-5 / 3 is approximately -1.6667. Rounding down gives -2. This differs from truncating toward zero, which would give -1.
Division-related assignment operators
Evaluation, reassignment, and types
The right-hand side is evaluated before the assignment updates the target. This makes statements such as the following predictable:
value = 4
value = value + 6
print(value) # 10
Python reads the current value of value, adds 6, and then reassigns the result to the same identifier. Assignment can also change the type bound to a variable.
data = 5 # data refers to an int
data = data / 2 # data now refers to a float
Remove the extra leading space in the second line when running this example:
data = 5
data = data / 2
print(data) # 2.5
print(type(data)) # <class 'float'>
The operands must support the requested operation. An unsupported combination raises TypeError.
amount = 5
# amount -= "3" # TypeError: a number cannot subtract text
Convert or validate values before updating them when their types may vary.
Mutable and immutable objects
An immutable object cannot be changed after it is created. Integers, floats, and strings are examples. An update involving an immutable value produces a new value and rebinds the variable.
A mutable object, such as a list, can be changed in place. When the type supports in-place augmented operation, += may modify the existing object rather than create a separate one. Other references to that object can therefore observe the change.
numbers = [1, 2]
alias = numbers
numbers += [3]
print(numbers) # [1, 2, 3]
print(alias) # [1, 2, 3]
This behavior is different from merely thinking of every augmented assignment as creating a completely new object. The exact behavior depends on the operand types and the operation they implement.
Common mistakes and troubleshooting
Using == when intending to update a variable
Symptom: The variable does not change, or the expression only produces True or False.
Fix: Use = for assignment and an augmented operator such as += for an update. Reserve == for comparisons.
Expecting /= to produce an integer quotient
Symptom: Dividing 5 by 3 stores approximately 1.6667, and the result is a float.
Fix: Use //= for floor division, while remembering that floor division rounds downward, especially for negative values.
Applying an operator to incompatible types
Symptom: Python raises TypeError, such as when subtracting text from a number.
Fix: Ensure both operands support the operation, or convert and validate the values before updating them.
Misunderstanding modulo assignment
Symptom: The result is a remainder instead of a decimal quotient.
Fix: Use %= when the remainder is required, /= for true division, or //= for floor division.
Unexpected mutation with a list and +=
Symptom: Another variable referring to the same list appears to change after an augmented update.
Fix: Remember that lists are mutable and may be updated in place. Use copy() when an independent list is needed.
Practice checklist
- Use
=to initialize or reassign a variable. - Use
==only to compare values. - Use
+=and-=for common counter and balance updates. - Use
*=and**=for multiplication and powers. - Choose
/=,//=, or%=according to whether you need a true quotient, a floor quotient, or a remainder. - Check operand types when an update raises
TypeError. - Be aware that augmented assignment with mutable objects can change an object shared by multiple variables.
For related comparisons, see Python comparison operators. To practice assignment with repetition and accumulation, review the Python for loop and the Python while loop.