You already know the basic assignment operator — =. This lesson covers the compound assignment operators: shortcuts that combine an arithmetic operation with assignment in one step.

Plain assignment

score: int = 10

That part you know. The variable on the left points to the value on the right.

Compound assignment

Often we want to modify a variable based on its current value:

score: int = 10
score = score + 5
print(score)   # 15

Python gives you a shorter way to write the same thing:

score: int = 10
score += 5
print(score)   # 15

score += 5 means “take the current value of score, add 5, and put the result back into score”.

Every arithmetic operator has a compound form:

x: int = 10

x += 3    # x = x + 3   → 13
x -= 5    # x = x - 5   → 8
x *= 2    # x = x * 2   → 16
x /= 4    # x = x / 4   → 4.0 (notice: now a float)
x //= 1   # x = x // 1  → 4.0
x %= 3    # x = x % 3   → 1.0
x **= 2   # x = x ** 2  → 1.0

Compound assignment with strings

Some compound operators also work on strings. += glues another string on; *= repeats:

greeting: str = "Hello"
greeting += ", World"
print(greeting)   # 'Hello, World'

stars: str = "*"
stars *= 5
print(stars)   # '*****'

Why use compound assignment?

Three reasons:

  1. Less typing. count += 1 is shorter than count = count + 1.
  2. Less to misread. With count = count + 1 the eye has to confirm both counts match. With count += 1 there’s only one place to look.
  3. Sometimes faster. For mutable types like lists, += updates in place rather than creating a new list. We’ll see this in Section 6.

Multiple assignment

Python lets you assign to several variables on one line:

x, y, z = 1, 2, 3
print(x, y, z)   # 1 2 3

This is called tuple unpacking — there’s actually a tuple (1, 2, 3) getting split into three variables. We’ll cover tuples in Section 6.

You can also give multiple names the same value:

a = b = c = 0
print(a, b, c)   # 0 0 0

A small but classic Python trick — swap two variables in one line, no temporary variable needed:

x: int = 1
y: int = 2

x, y = y, x
print(x, y)   # 2 1

The walrus operator (briefly)

Python 3.8 added a special assignment operator, :=, called the walrus because it looks like one. It lets you assign and use a value in the same expression:

# without walrus
data = input("Enter text: ")
while data != "quit":
    print(f"Got: {data}")
    data = input("Enter text: ")

# with walrus
while (data := input("Enter text: ")) != "quit":
    print(f"Got: {data}")

It’s useful, but easy to overuse. We’ll mostly stick to the longer form in this course — it’s clearer for beginners.

What’s next

You can update variables with one symbol instead of three. Next, two operators that work with collections — membership (in) and identity (is).

Toggle theme (T)