VMware ESXi and vSphere Cluster Management

Python Assignment Operators

Learn how Python assignment operators store values, reassign variables, and update numbers, strings, and lists with operators such as +=, -=, /=, %=, and //=.

Assignment operators let a Python program store a value in a variable or update a value that is already stored. The basic assignment operator is =. Python also provides augmented assignment operators such as += and *= for combining an operation with assignment.

What assignment means in Python

Assignment binds a value to a variable or another valid assignment target. The expression on the right-hand side is evaluated first. Python then stores or binds the resulting value to the target on the left-hand side.

price = 12
quantity = 3
total = price * quantity
print(total)  # 36

In this example, price * quantity is an expression. It produces the value 36, which is then assigned to total.

The direction is important: assignment goes from right to left. The left-hand side receives the result; it is not evaluated as a value to copy to the right.

Assignment is not comparison

= assigns a value. == compares two values and produces True or False.

score = 10          # Assignment
score == 10         # Comparison; produces True

if score == 10:
    print("The score is 10")

Using = when you mean to compare values usually causes a syntax error in a conditional. Use == for equality comparison.

Basic assignment with =

You can assign integers, floating-point numbers, strings, Boolean values, and the results of expressions.

age = 21
price = 19.99
name = "Mina"
is_logged_in = True

subtotal = price * 2
print(subtotal)  # 39.98

A variable can be assigned a new value later. This is called reassignment.

score = 40
score = 75
print(score)  # 75

The second assignment replaces the value currently associated with score. A variable must receive an initial value before an update such as score += 5 can use its current value.

Augmented assignment

Augmented assignment combines an operation with assignment. Its general form is:

variable operator= value

For a simple variable, total += amount is conceptually similar to reading the current value, adding amount, and assigning the result back:

total = total + amount

The augmented form is commonly used for counters, running totals, balances, inventory, and other accumulators. The expanded form is a useful way to understand the operation, although Python's augmented operators can have type-specific behavior for mutable objects.

Python assignment operators reference

Operator | Meaning | Simple-variable equivalent | Example | Result

= | Assign a value | x = 5 | x = 5 | 5

+= | Add and assign | x = x + 3 | 5; x += 3 | 8

-= | Subtract and assign | x = x - 3 | 5; x -= 3 | 2

*= | Multiply and assign | x = x * 3 | 5; x *= 3 | 15

/= | Divide and assign | x = x / 3 | 5; x /= 3 | 1.6666666666666667

%= | Calculate the remainder and assign | x = x % 3 | 5; x %= 3 | 2

**= | Raise to a power and assign | x = x ** 3 | 5; x **= 3 | 125

//= | Floor-divide and assign | x = x // 3 | 5; x //= 3 | 1

Addition assignment: +=

+= adds the right-hand operand to the current value and assigns the result back to the left-hand target.

points = 10
points += 7
print(points)  # 17

cart_total = 25.50
cart_total += 4.75
print(cart_total)  # 30.25

+= also works with compatible sequences. With strings it concatenates text, and with lists it adds compatible elements to the sequence.

message = "Hello"
message += "!"
print(message)  # Hello!

items = ["pen"]
items += ["notebook"]
print(items)  # ['pen', 'notebook']

Subtraction assignment: -=

-= subtracts the right-hand operand from the current left-hand value and assigns the result back.

stock = 20
stock -= 6
print(stock)  # 14

balance = 100.00
balance -= 12.50
print(balance)  # 87.5

Multiplication assignment: *=

*= multiplies the current value by the right-hand operand and stores the product.

price = 15
price *= 3
print(price)  # 45

recipe_amount = 2
recipe_amount *= 4
print(recipe_amount)  # 8

For compatible sequences, multiplication assignment can repeat the sequence.

text = "ha"
text *= 3
print(text)  # hahaha

pattern = [0, 1]
pattern *= 2
print(pattern)  # [0, 1, 0, 1]

Division assignment: /=

/= divides the current value by the right-hand operand and assigns the quotient. In Python 3, / performs true division and normally produces a floating-point result, even when both starting operands are integers.

value = 5
value /= 3
print(value)       # 1.6666666666666667
print(type(value)) # <class 'float'>

Use /= when a fractional result is appropriate. If you need floor division, use //= instead.

Modulus assignment: %=

Modulus calculates the remainder after division. The operator %= stores that remainder.

remaining = 5
remaining %= 3
print(remaining)  # 2

Remainders are useful for checking parity, detecting repeating cycles, and wrapping a value within a fixed range.

position = 7
position %= 4
print(position)  # 3

number = 14
is_even = number % 2 == 0
print(is_even)  # True

In Python, % is remainder arithmetic in an expression. It is not percentage notation.

Exponentiation assignment: **=

Exponentiation raises a value to a power. The operator **= performs that operation and stores the result.

value = 5
value **= 3
print(value)  # 125

This is conceptually equivalent to value = value ** 3 for a simple variable.

Floor-division assignment: //=

//= stores the result of floor division. Floor division rounds the quotient down toward negative infinity. It does not simply remove the decimal portion in every case.

groups = 5
groups //= 3
print(groups)  # 1

For positive numbers, this often looks like truncation. Negative values show the difference:

value = -5
value //= 3
print(value)  # -2

The mathematical quotient is about -1.6667. Rounding down toward negative infinity gives -2. Truncating toward zero would give -1, so those are different operations.

Comparing division-related operators

Operator | Operation | Example starting value and operand | Stored result | Key behavior

/= | True division | 5; /= 3 | 1.6666666666666667 | Normally produces a float in Python 3.

//= | Floor division | 5; //= 3 | 1 | Rounds down toward negative infinity.

%= | Remainder | 5; %= 3 | 2 | Stores what remains after division.

Practical accumulator examples

Updating a running total

total = 0
total += 12.50
total += 8.25
total += 4.00
print(total)  # 24.75

Reducing available stock

available = 50
used = 13
available -= used
print(available)  # 37

Dividing a total into equal shares

total = 10
people = 3
total /= people
print(total)       # 3.3333333333333335
print(type(total)) # <class 'float'>

Wrapping a position in a repeating range

position = 9
position %= 6
print(position)  # 3

A program can use this pattern for repeating indexes, rotating turns, or positions in a cycle.

Counting complete groups

items = 17
group_size = 5
items //= group_size
print(items)  # 3

The result is the number of complete groups, with any incomplete remainder discarded by floor division for these positive values.

Behavior with mutable and immutable values

Integers, floating-point numbers, and strings are immutable values: their contents cannot be changed in place. An augmented assignment involving one of these values produces a resulting value and rebinds the variable.

Mutable objects such as lists can have type-specific augmented-assignment behavior. For example, list += commonly extends the existing list with elements from another compatible iterable.

numbers = [1, 2]
numbers += [3, 4]
print(numbers)  # [1, 2, 3, 4]

Do not assume that every object supports every augmented operator. The types of the current value and right-hand operand must support the selected operation.

Common mistakes and troubleshooting

Using = instead of ==

If a conditional raises a syntax error or does not express the intended test, check whether assignment was used instead of equality comparison.

temperature = 20
if temperature == 20:
    print("Exactly 20 degrees")

Expecting /= to keep an integer

/= uses true division, so a decimal result is normal. Use //= only when floor-division behavior is intended.

Confusing %= with percentages

%= stores a division remainder. For example, 5 %= 3 leaves 2; it does not calculate five percent.

Updating an uninitialized variable

An augmented assignment reads the current value first. If no value has been assigned, Python raises NameError.

count = 0
count += 1
print(count)  # 1

Using incompatible operand types

An augmented assignment can raise TypeError when the operands do not support the selected operation together.

count = 3
# count += " items"  # TypeError: incompatible numeric and string values

Check the types with type() and convert data deliberately when that conversion makes sense.

x = 5
x += 3
print(x)
print(type(x))

Misunderstanding negative floor division

Remember that // rounds downward toward negative infinity. Test negative inputs explicitly when the rounding rule matters.

Assignment operators versus other operators

Augmented assignment operators update a target. They are different from comparison operators such as == and <, logical operators such as and and or, and membership operators such as in. Those other operator families answer questions or combine conditions rather than storing an updated value.

Practice checklist

  • Identify the left-hand target and right-hand expression in an assignment.
  • Explain why the right-hand expression is evaluated before the result is stored.
  • Use = for initial assignment and reassignment.
  • Use +=, -=, *=, /=, %=, **=, and //= to update compatible values.
  • Inspect a result with print() and inspect its type with type().
  • Initialize a variable before applying augmented assignment.