← Python lessons

Python Walrus Operator (:=) in while Loops

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

The walrus operator := stores a value and gives it back in the same expression. In a while condition, it lets you get the next value and test it in one step.

Read While Loops first. The examples also use pop(0) from Lists, which removes and returns the first item, and one uses try and except from try and except. Every block runs on its own with fixed data, and its output is described under it.

Get and test a value in one condition

(word := words.pop(0)) removes the first word, stores it in word, and gives it to != to compare.

words = ["red", "blue", "stop", "green"]
while (word := words.pop(0)) != "stop":
    print(word)

This prints red and blue. The loop ends at stop, so green is never read.

Compare it with the version without :=

Without the walrus, you fetch the first value before the loop and again at the end of the body.

words = ["red", "blue", "stop", "green"]
word = words.pop(0)
while word != "stop":
    print(word)
    word = words.pop(0)

Both print the same. The walrus version writes the fetch once, so the two copies can't drift apart. Use the longer version when your readers don't know := yet.

Keep the brackets

Without brackets, := takes everything to its right. Here word gets the result of the comparison, not the word.

words = ["red", "stop"]
while word := words.pop(0) != "stop":
    print(word)

This prints True, not red. Always wrap the assignment in brackets when you compare it.

Plan for running out

If the stop value never comes, pop(0) reaches an empty list and fails.

words = ["red", "blue"]
try:
    while (word := words.pop(0)) != "stop":
        print(word)
except IndexError:
    print("Ran out before stop")

This prints red, blue, then Ran out before stop. Test for an empty list too when the stop value is not guaranteed.

Read input until a blank line

The common real use is reading input until the user enters nothing. This block needs typed input, so it is shown without Run.

while (line := input("Item: ")) != "":
    print("Added", line)

Note: := needs Python 3.8 or later. It works in if conditions and comprehensions too, but use it only where it removes a repeated line. These examples use fixed lists in place of input.

See also: break and continue, Processing a work list.

Your turn

Print each reading until you reach a 0, then print done. Use := in the while condition.

readings = [4, 7, 0, 9]
# add a while loop with := that prints each reading before the 0
print("done")

Expected output

4
7
done