Control Flow
Assignment Expressions
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 6The 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
okNotes
name := expressionassigns and evaluates to the assigned value.- Use it to avoid computing the same value twice.
- Prefer a normal assignment when the expression becomes hard to scan.
See also
- contrast: Conditionals
- related: While Loops
- prerequisite: Variables
Run the complete example
Expected output
hello 5
python 6
retry
ok
Execution time appears here after you run the example.