Control Flow

Assignment Expressions

The walrus operator assigns a value inside an expression.

An assignment expression can name a computed value while a condition tests it. Here empty strings are skipped because their length is zero.

Source

messages = ["hello", "", "python"]

for message in messages:
    if length := len(message):
        print(message, length)

Output

hello 5
python 6
NAME FACTlen(xs):=nn > 10DISPATCH SHAPEvaluecase intcase [x,y]case _
The walrus binds a name during the surrounding expression; one expression, two outputs.

The same idea works in loops that read state until a sentinel appears. The assignment and comparison stay together.

Source

queue = ["retry", "ok"]
while (status := queue.pop(0)) != "ok":
    print(status)
print(status)

Output

retry
ok

Notes

See also

Run the complete example

Example code

Expected output

hello 5
python 6
retry
ok

Execution time appears here after you run the example.