Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 149 ยท Operators

Assignment Operators and the Walrus

Update variables with Python's augmented assignment operators like += and *=, see how they behave with lists and strings, and learn when the walrus operator := helps.

Most variables change over a program's life. A score goes up, a balance goes down, a message grows line by line. Writing score = score + 10 works, but it repeats the variable name and gets tiring. Python's augmented assignment operators such as += do the same job in a shorter, clearer way.

This lesson also covers the walrus operator :=, added in Python 3.8. It assigns a value inside an expression, which removes some awkward repetition in loops and conditions. It's powerful, and it's easy to overuse, so you'll learn where it shines and where to leave it out.

Plain assignment, quickly revisited

The single = binds a name to a value, as you saw in Variables and Names. Python evaluates the right-hand side first, then stores the result:

Python
count = 0
count = count + 1   # read count, add 1, store the result back in count
x = y = 0           # chained: both names refer to 0
width, height = 1920, 1080   # multiple assignment

The count = count + 1 line looks odd as math, but it makes sense as an instruction: "take the current value, add one, and store it back".

Augmented assignment operators

Each arithmetic operator from Arithmetic Operators has an augmented version that combines the operation with assignment:

Operator Same as Example (x = 10) New x
+= x = x + n x += 3 13
-= x = x - n x -= 3 7
*= x = x * n x *= 3 30
/= x = x / n x /= 4 2.5
//= x = x // n x //= 4 2
%= x = x % n x %= 4 2
**= x = x ** n x **= 2 100

There are also bitwise versions (&=, |=, ^=, >>=, <<=); you'll meet |= with sets and dictionaries later.

Python Updating a score

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that /= changes the type to float, exactly as / does. Augmented operators follow the same rules as their plain versions.

There's no ++ or -- in Python. count++ is a SyntaxError, and ++count is valid but does nothing useful (it's just two unary plus signs). Write count += 1.

Note: The variable must exist before you can update it. total += 5 on a name that was never assigned raises NameError, because Python has to read the old value first.

Accumulating results

The most common use of += is building up a result inside a loop: a running total, a counter, or a growing string. You'll learn loops properly in for Loops; here's a preview:

Python Running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tip: Building a long string with += in a loop is fine for a few dozen pieces. For thousands, collect the pieces in a list and call "".join(parts) once at the end; it's faster and just as clear. See String Methods.

+= on lists changes the original

For immutable values like numbers, strings and tuples, x += y creates a new object and rebinds x to it. For mutable objects like lists, += modifies the object in place. That difference shows up when two names refer to the same list:

Python Mutable vs immutable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

After cart += ["eggs"], both names see the change, because += extended the one list they share. After cart = cart + ["bread"], cart points to a brand-new list and shared keeps the old one. You'll understand this fully after Membership and Identity Operators and Lists; for now, remember that += on a list behaves like .extend().

The walrus operator :=

The assignment expression operator := is nicknamed the walrus because := looks like a walrus's eyes and tusks. Unlike =, which is a statement, := is an expression: it assigns a value and returns that value, so you can use it in the middle of a condition.

It solves a specific problem: computing a value, testing it, and then using it, without calling the function twice or adding an extra line.

Python Walrus in an if statement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The parentheses matter. Without them, length := len(comment) > 40 would store the Boolean result of the comparison, because := has the lowest precedence of all operators.

Where the walrus shines: loops

The walrus is most helpful in while loops that read a value, check it, and process it. Here a program reads commands until the user types quit:

Python Reading until a sentinel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without := you'd have to call input() once before the loop and again at the bottom of the loop body. The walrus keeps the read, the test and the assignment together. while loops get their own lesson in while Loops.

It also helps in comprehensions, when you'd otherwise compute something twice:

Python
words = ["sky", "mountain", "sea", "waterfall"]
long_words = [(w, n) for w in words if (n := len(w)) > 5]
# [('mountain', 8), ('waterfall', 9)]

When not to use it

You can't use := as a plain statement at the top level; x := 5 on its own line is a SyntaxError. Python wants you to write x = 5 there. More generally, use the walrus only when it removes real repetition. A line like print(total := price * qty) saves nothing and hides an assignment inside a function call. If a reader has to pause to work out where a variable came from, a separate line is better.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After x = 7 and then x %= 3, what is x?

    x %= 3 means x = x % 3, and 7 % 3 is 1.
  2. 2. How do you add 1 to count in Python?

    Python has no ++ operator. count =+ 1 is valid but sets count to +1. The correct form is count += 1.
  3. 3. After a = [1], b = a, a += [2], what is b?

    += on a list extends it in place, and b refers to the same list.
  4. 4. In if (n := len(data)) > 10:, what does n hold?

    The parentheses make n := len(data) run first, so n gets the length. The name stays available after the if statement.

Summary

  • = evaluates the right side, then binds the name; x = y = 0 and a, b = 1, 2 are also valid.
  • Augmented operators (+=, -=, *=, /=, //=, %=, **=) update a variable in place of x = x op y.
  • Python has no ++ or --; write x += 1.
  • On lists, += extends the existing list, so every name sharing it sees the change.
  • The walrus := assigns inside an expression and returns the value; wrap it in parentheses in comparisons.
  • Use the walrus to avoid repeated calls in while loops and comprehensions, not to squeeze code onto one line.

Next: Membership and Identity Operators, where you'll test what a collection contains and whether two names point to the same object.